diff --git a/.github/workflows/test_cuda.yml b/.github/workflows/test_cuda.yml index 91ede5d975..985973e8f5 100644 --- a/.github/workflows/test_cuda.yml +++ b/.github/workflows/test_cuda.yml @@ -211,6 +211,7 @@ jobs: source/install/test_cc_local.sh --build-only source/install/test_cc_local.sh --models-only=kokkos env: + LAMMPS_VERSION: patch_4Jul2026 CMAKE_GENERATOR: Ninja DP_VARIANT: cuda ENABLE_PADDLE: FALSE diff --git a/deepmd/calculator.py b/deepmd/calculator.py index 402e09ba77..9cb5aa534e 100644 --- a/deepmd/calculator.py +++ b/deepmd/calculator.py @@ -67,6 +67,9 @@ def _compress_dpa4c_for_ase(model: Any) -> bool: from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( compression_ineligibility_reason, ) + from deepmd.pt_expt.utils.serialization import ( + compressed_export_unsupported_reason, + ) parts = model.atomic_model.fused_decomposition() if ( @@ -76,6 +79,8 @@ def _compress_dpa4c_for_ase(model: Any) -> bool: ): return False reason = compression_ineligibility_reason(parts[0].descriptor) + if reason is None: + reason = compressed_export_unsupported_reason(model) if reason is None: return True log.warning( diff --git a/deepmd/dpmodel/descriptor/dpa4c.py b/deepmd/dpmodel/descriptor/dpa4c.py index d43c9255bd..bec7c9f5fa 100644 --- a/deepmd/dpmodel/descriptor/dpa4c.py +++ b/deepmd/dpmodel/descriptor/dpa4c.py @@ -13,10 +13,12 @@ probes couple every non-scalar degree triple allowed by the O(3) triangle and parity rules. -Evaluation is a single destination-local scan: one payload carries both -envelope masses and every degree-wise moment. The descriptor therefore -constructs no neighbor pairs, Wigner rotations, or source-node features, and -reduces the edge axis exactly once. +With one message-passing block, evaluation is a single destination-local +scan: one payload carries both envelope masses and every degree-wise moment. +The descriptor then constructs no neighbor pairs, Wigner rotations, or +source-node features, and reduces the edge axis exactly once. Every further +block reads per-node features of the edge sources through an attention and +reduces the same edges once more. """ from __future__ import ( @@ -24,6 +26,7 @@ ) import dataclasses +import itertools import math from typing import ( TYPE_CHECKING, @@ -58,6 +61,9 @@ from deepmd.dpmodel.utils.update_sel import ( UpdateSel, ) +from deepmd.utils.block_cutoff import ( + resolve_block_cutoffs, +) from deepmd.utils.bridging import ( check_window_inside_cutoff, ) @@ -81,10 +87,12 @@ RadialBasis, SeZMTypeEmbedding, SwiGLUMLP, + compute_source_gates, pair_contact, resolve_swiglu_hidden_width, ) from .dpa4c_nn import ( + BlockAttention, ChargeStateEmbedding, InvariantReadout, OrderedPairFiLM, @@ -139,7 +147,22 @@ class DescrptDPA4C(NativeOP, BaseDescriptor): fixed O(3)-even Cartesian bispectrum over low-rank probes, and the projected quartic. - Two further blocks close the output. The divisors + Every block after the first passes one message from the edge sources. + Block :math:`k` rescales every amplitude of the first block by the attention + factor :math:`m^k_{ijc}\in(0,2)` of the edge source in block :math:`k-1`, + which relaxes to one at the cutoff of block :math:`k`, reduces every + degree again under the neighborhood normalizers of the first block, and + adds the keys of the neighbors that the attention transports + (:class:`~deepmd.dpmodel.descriptor.dpa4c_nn.BlockAttention`): + + .. math:: + + X^{(\ell),k}_{ic}=n^{(+)}_i\sum_j\chi_{ij}m^{k}_{ijc}\phi_{ijc} + B^{(\ell)}(\hat{\mathbf r}_{ij})+\Delta X^{(\ell),k}_{ic}. + + The readout acts on the moments of the last block. + + Two further output blocks close the descriptor. The divisors :math:`1/n^{(0)}` and :math:`1/n^{(+)}` are emitted alongside the invariants, because normalization is otherwise irreversible and the effective coordination they encode would reach neither the readout nor the @@ -149,7 +172,10 @@ class DescrptDPA4C(NativeOP, BaseDescriptor): Parameters ---------- rcut - Outer cutoff radius in Å. + Cutoff radius in Å shared by every block, or one non-increasing cutoff + per block. The first cutoff bounds the neighbor graph and the radial + representation; the cutoff of every further block is where its factor + relaxes to one. ntypes Number of atom types. channels @@ -167,6 +193,10 @@ class DescrptDPA4C(NativeOP, BaseDescriptor): Number :math:`R` of shared radial mode profiles that every ordered atom-type pair mixes with its own coefficients. Zero leaves each pair with a rescaled copy of one shared radial function. + n_blocks + Number of message-passing blocks. The first block is the one-hop + reduction; every further block passes one message from the edge + sources. use_amp Whether the per-edge stage runs under bfloat16 automatic mixed precision on CUDA during training. This is an execution policy rather @@ -221,9 +251,11 @@ class DescrptDPA4C(NativeOP, BaseDescriptor): TypeError If ``channels`` or ``lmax`` is not an integer. ValueError - If ``rcut``, ``ntypes``, or ``n_radial`` is not positive, if - ``radial_modes`` is negative, if ``channels`` or ``lmax`` is outside - its supported set, if only one bridging radius is given, if + If a cutoff, ``n_blocks``, ``ntypes``, or ``n_radial`` is not + positive, if ``rcut`` lists a cutoff count other than ``n_blocks``, + if the cutoffs increase, if ``radial_modes`` is negative, if + ``channels`` or ``lmax`` is outside its supported set, if only one + bridging radius is given, if ``inner_clamp_scale`` is neither ``"covalent"`` nor ``"absolute"``, or if a covalent window is asked for without a ``type_map`` covering every type. @@ -258,15 +290,18 @@ class DescrptDPA4C(NativeOP, BaseDescriptor): "coupling_value", "output_mean", "output_inv_std", + "blocks", ) # The low-rank radial table and its expansion, which a payload compressed # without that table does not carry; empty artifacts select the radial - # table itself, so such a payload loads as the snapshot it was. - _OPTIONAL_COMPRESSION_BUFFER_NAMES = ("basis_table", "basis_matrix") + # table itself, so such a payload loads as the snapshot it was. A payload + # of a single-block descriptor compressed before further blocks existed + # carries no block records either, and an empty array denotes one block. + _OPTIONAL_COMPRESSION_BUFFER_NAMES = ("basis_table", "basis_matrix", "blocks") def __init__( self, - rcut: float, + rcut: float | list[float], ntypes: int, channels: int = 32, lmax: int = 2, @@ -286,6 +321,7 @@ def __init__( inner_clamp_f_inner: float | None = None, inner_clamp_f_outer: float | None = None, inner_clamp_scale: str = "covalent", + n_blocks: int = 1, ) -> None: # === Step 1. Validate the public architecture contract === if spin is not None: @@ -293,8 +329,11 @@ def __init__( "DPA4C configures native spin through `use_spin`; the `spin` " "argument of the common descriptor ABI is not supported." ) - if rcut <= 0.0: - raise ValueError(f"`rcut` must be positive, got {rcut}") + block_rcut = resolve_block_cutoffs(rcut, n_blocks) + if any(inner > outer for outer, inner in itertools.pairwise(block_rcut)): + raise ValueError( + f"The block cutoffs in `rcut` must not increase, got {rcut}" + ) if ntypes <= 0: raise ValueError(f"`ntypes` must be positive, got {ntypes}") if n_radial <= 0: @@ -326,7 +365,11 @@ def __init__( bispectrum_ranks = derive_bispectrum_ranks(degree_channels) # === Step 2. Resolve the scalar configuration === - self.rcut = float(rcut) + # The first cutoff bounds the neighbor graph and the radial + # representation; every further block acts on a subset of its edges. + self.block_rcut = block_rcut + self.n_blocks = len(block_rcut) + self.rcut = block_rcut[0] self.ntypes = int(ntypes) self.channels = int(channels) self.lmax = int(lmax) @@ -463,6 +506,29 @@ def __init__( if self.add_chg_spin_ebd else None ) + # Every further block owns its attention and the C³ envelope of its + # cutoff. The encoders read the complete calibrated descriptor of the + # previous block, spin invariants included. + descriptor_dim = self.get_dim_out() + attention_seed = child_seed(seed, 7) + self.attentions = [ + BlockAttention( + self.degree_channels, + descriptor_dim, + precision=self.precision, + trainable=self.trainable, + seed=child_seed(attention_seed, block), + ) + for block in range(1, self.n_blocks) + ] + self.block_envelopes = [ + C3CutoffEnvelope( + rcut=block_cutoff, + exponent=self._ENVELOPE_EXPONENT, + precision=self.precision, + ) + for block_cutoff in self.block_rcut[1:] + ] # === Step 4. Lay out the flat moment payload === # Degree zero owns the leading `channels` entries of the flat layout, @@ -514,9 +580,12 @@ def call_graph( ``(ntypes + 1, channels)``. If omitted, the descriptor evaluates its type-embedding module. comm_dict - Communication metadata accepted by the common graph ABI. DPA4C - does not read source-node features, so no halo-feature exchange is - required and this argument is unused. + Border-exchange tensors of a domain-decomposed graph whose nodes + are the owned atoms followed by ghost images. A single-block + descriptor reads no source-node feature and ignores it; every + further block refreshes the ghost rows of the source features + from their owners through it, and a bridged multi-block descriptor + completes its source gate through it. spin Per-node spin vectors with shape ``(N, 3)`` on the same flat node axis as ``atype``, including ghost and padding rows. Mandatory @@ -542,7 +611,6 @@ def call_graph( If the descriptor is spin conditioned and ``spin`` is absent, or charge conditioned with neither ``charge_spin`` nor a default. """ - del comm_dict # === Step 1. Resolve type features and compute precision === if type_embedding is None: type_embedding = self.type_embedding.call() @@ -564,6 +632,7 @@ def call_graph( self.require_charge_spin( charge_spin, graph.n_node.shape[0], graph.edge_vec ), + comm_dict=comm_dict, ) # === Step 3. Restore the graph input dtype === @@ -671,8 +740,8 @@ def call( fparam Frame parameters accepted by the common descriptor ABI; unused. comm_dict - Communication metadata accepted by the common descriptor ABI; - unused. + Communication metadata; unsupported by this dense adapter. + Cross-rank exchange requires the graph lower. charge_spin Frame-level total charge and spin multiplicity with shape ``(F, 2)``. Read only when the descriptor is configured with @@ -697,7 +766,12 @@ def call( graph_from_dense_quartet, ) - del fparam, comm_dict + del fparam + if comm_dict is not None: + raise NotImplementedError( + "DPA4C cross-rank communication requires the graph lower; " + "the dense adapter does not support comm_dict." + ) xp = array_api_compat.array_namespace(coord_ext, atype_ext, nlist) nf, nloc, nnei = nlist.shape @@ -733,11 +807,13 @@ def evaluate_graph( type_embedding: Array, spin: Array | None = None, charge_spin: Array | None = None, + comm_dict: dict | None = None, ) -> tuple[Array, Array]: """Evaluate the graph-native descriptor equations. The pipeline is edge amplitudes, one destination reduction into - degree-wise moments, and the fixed invariant readout. + degree-wise moments, one further reduction per further + message-passing block, and the fixed invariant readout. Parameters ---------- @@ -753,6 +829,11 @@ def evaluate_graph( charge_spin Canonical frame conditions with shape ``(nf, 2)``, mandatory for a charge-conditioned descriptor and ignored otherwise. + comm_dict + Border-exchange tensors of a domain-decomposed graph, or ``None``. + Without communication, every source node must carry its complete + neighborhood. ``n_local`` specifies energy ownership, not whether + a node has a complete neighborhood. Returns ------- @@ -826,6 +907,7 @@ def evaluate_graph( pair_latent, edge_hidden_bias, conditioned_spin, + comm_dict, ) # === Step 5. Reduce the degree-wise moments === @@ -841,7 +923,20 @@ def evaluate_graph( n_total, ) - # === Step 6. Build calibrated invariant features === + # === Step 6. Run the further message-passing blocks === + if self.attentions: + moments = self.run_further_blocks( + graph, + moments, + center_type_embedding, + divisors, + amplitude, + basis, + envelope, + comm_dict, + ) + + # === Step 7. Build calibrated invariant features === return ( self.build_invariant_descriptor( moments, @@ -851,6 +946,79 @@ def evaluate_graph( envelope[:, None], ) + def run_further_blocks( + self, + graph: Any, + moments: Array, + center_type_embedding: Array, + divisors: Array, + amplitude: Array, + basis: Array, + envelope: Array, + comm_dict: dict | None, + ) -> Array: + """Run every block after the first and return the final moments. + + Each block rescales the amplitudes of the first one by the attention + of the edge source in the previous block, reduces every degree again + under the envelope masses and normalizers of the first one, and adds + the transported keys of the neighbors. The ghost rows of a + domain-decomposed graph receive no edges, so their source features + are refreshed from the owners. + + Parameters + ---------- + graph + Neighbor graph in descriptor compute precision. + moments + Moments of the first block with shape ``(N, S')``. + center_type_embedding + Center type features with shape ``(N, channels)``. + divisors + Neighborhood divisors of the first block with shape ``(N, 2)``. + amplitude + Enveloped first-block edge amplitudes with shape ``(E, channels)``. + basis + Masked Cartesian harmonics with shape ``(E, (lmax + 1) ** 2)``. + envelope + Masked C³ envelope of the first block with shape ``(E,)``. + comm_dict + Border-exchange tensors of a domain-decomposed graph, or ``None``. + + Returns + ------- + Array + Moments of the last block with the shape of ``moments``. + """ + xp = array_api_compat.array_namespace(graph.edge_vec) + src, dst = graph.edge_index[0], graph.edge_index[1] + distance = xp.sqrt( + xp.sum(graph.edge_vec * graph.edge_vec, axis=-1) + self._EPS * self._EPS + ) + for attention, block_envelope in zip( + self.attentions, self.block_envelopes, strict=True + ): + invariants = self.build_invariant_descriptor( + moments, center_type_embedding, divisors + ) + sources = attention.source_features(moments, invariants) + if comm_dict is not None: + sources = self.exchange_ghost_rows(sources, comm_dict) + block_amplitude, transport = attention.call( + sources, + attention.center_features(invariants), + amplitude, + basis, + envelope, + block_envelope.call(distance), + src, + dst, + ) + moments = self.reduce_moments( + block_amplitude, basis, envelope, dst, divisors, moments, transport + ) + return moments + def build_center_type_features( self, type_embedding: Array, @@ -940,6 +1108,7 @@ def build_edge_features( pair_latent: tuple[Array, Array], edge_hidden_bias: Array | None = None, conditioned_spin: Array | None = None, + comm_dict: dict | None = None, ) -> tuple[Array, Array, Array, Array | None]: r"""Build the enveloped edge amplitudes, harmonics, and spin payload. @@ -975,6 +1144,10 @@ def build_edge_features( conditioned_spin Conditioned per-node spin with shape ``(N, 3)``, or ``None`` for a spin-free descriptor. + comm_dict + Border-exchange tensors of a domain-decomposed graph, through + which a bridged multi-block descriptor completes its source gate, or + ``None``. Returns ------- @@ -1021,10 +1194,33 @@ def build_edge_features( # switch reads the true pair length, and the radial features read the # clamped one, which moves at the rate the switch has opened. The # direction keeps the true geometry. + # + # A further block reads the state of the edge source, so it would + # carry a close pair to third atoms: a neighbor C of A sees both A and + # B, and its features would return B to the environment of A. A + # multi-block descriptor therefore also mutes every edge that a frozen + # atom emits towards a third atom, through the leave-one-out source + # gate of DPA4, so a frozen atom leaves every other environment while + # its own pair edge is closed by the switch of that edge. inner_switch = None if self.bridging_switch is not None: contact = self.pair_contact(center_type, neighbor_type, distance.dtype) inner_switch = self.bridging_switch.call(distance, contact) + if self.attentions: + _, source_gate = compute_source_gates( + edge_len=distance, + edge_contact=contact, + src=src, + n_nodes=atype.shape[0], + bridging_switch=self.bridging_switch.call, + edge_keep_f=mask, + node_partial_exchange=None + if comm_dict is None + else lambda partials: self.complete_node_partials( + partials, comm_dict + ), + ) + inner_switch = inner_switch * source_gate distance = self.bridging_clamp.call(distance, contact) envelope = self.evaluate_cutoff_envelope(distance) if inner_switch is not None: @@ -1148,30 +1344,16 @@ def aggregate_moments( ) xp = array_api_compat.array_namespace(amplitude) - n_edge = amplitude.shape[0] # Payload layout: [chi^2, chi^4, degree zero (C_0), degrees one and # above (S - C_0)]. Degree zero is the whole edge amplitude under its - # single envelope. Degree l is the outer product of its 2l + 1 - # harmonics with the leading C_l channels of the amplitude, laid out - # harmonic-major and carrying a second envelope. The products are - # formed by broadcasting, so their backward reduces over the - # broadcast axes. - angular = [ - xp.reshape( - basis[:, degree * degree : (degree + 1) * (degree + 1), None] - * amplitude[:, None, :width], - (n_edge, (2 * degree + 1) * width), - ) - for degree, width in enumerate(self.degree_channels) - if degree > 0 - ] + # single envelope; every higher degree carries a second envelope. envelope_squared = envelope * envelope parts = [ envelope_squared[:, None], (envelope_squared * envelope_squared)[:, None], amplitude, - xp.concat(angular, axis=1) * envelope[:, None], + self.build_angular_payload(amplitude, basis, envelope), ] if spin_payload is not None: parts.append(spin_payload) @@ -1188,6 +1370,109 @@ def aggregate_moments( normalized.append(spin_onsite) return xp.concat(normalized, axis=1), divisors + def reduce_moments( + self, + amplitude: Array, + basis: Array, + envelope: Array, + dst: Array, + divisors: Array, + moments: Array, + transport: Array, + ) -> Array: + """Reduce the geometric moments of a further block. + + The block rescales the amplitudes but keeps the envelope masses of the + first reduction, so it reuses their divisors, and the moments equal + those of :meth:`aggregate_moments` when every factor is one and the + transport vanishes. The spin moments, when present, are not rescaled + and keep the values of the previous block. + + Parameters + ---------- + amplitude + Rescaled edge amplitudes with shape ``(E, channels)``. + basis + Masked Cartesian harmonics with shape ``(E, (lmax + 1) ** 2)``. + envelope + Masked C³ envelope with shape ``(E,)``. + dst + Destination node indices with shape ``(E,)``. + divisors + Neighborhood divisors of :meth:`aggregate_moments` with shape + ``(N, 2)``. + moments + Moments of the previous block with shape ``(N, S')``, whose + columns past the geometric degrees are carried over. + transport + Transported non-scalar moments added after normalization, with + shape ``(N, S - channels)``. + + Returns + ------- + Array + Moments with the shape of ``moments``. + """ + from deepmd.dpmodel.utils.neighbor_graph import ( + segment_sum, + ) + + xp = array_api_compat.array_namespace(amplitude) + payload = xp.concat( + [amplitude, self.build_angular_payload(amplitude, basis, envelope)], + axis=1, + ) + reduced = segment_sum(payload, dst, divisors.shape[0]) + directional = reduced[:, self.channels :] / divisors[:, 1:] + transport + return xp.concat( + [ + reduced[:, : self.channels] / divisors[:, :1], + directional, + moments[:, self.degree_offsets[-1] :], + ], + axis=1, + ) + + def build_angular_payload( + self, + amplitude: Array, + basis: Array, + envelope: Array, + ) -> Array: + """Build the enveloped edge payload of every non-scalar degree. + + Degree l is the outer product of its 2l + 1 harmonics with the leading + C_l channels of the amplitude, laid out harmonic-major and carrying a + second envelope factor. The products are formed by broadcasting, so + their backward reduces over the broadcast axes. + + Parameters + ---------- + amplitude + Masked edge amplitudes with shape ``(E, channels)``. + basis + Masked Cartesian harmonics with shape ``(E, (lmax + 1) ** 2)``. + envelope + Masked C³ envelope with shape ``(E,)``. + + Returns + ------- + Array + Payload with shape ``(E, S - channels)``. + """ + xp = array_api_compat.array_namespace(amplitude) + n_edge = amplitude.shape[0] + angular = [ + xp.reshape( + basis[:, degree * degree : (degree + 1) * (degree + 1), None] + * amplitude[:, None, :width], + (n_edge, (2 * degree + 1) * width), + ) + for degree, width in enumerate(self.degree_channels) + if degree > 0 + ] + return xp.concat(angular, axis=1) * envelope[:, None] + def build_invariant_descriptor( self, moments: Array, @@ -1262,6 +1547,58 @@ def build_invariant_descriptor( # A backend wrapper overrides these to reach native kernels; the equations # above stay array-API neutral. + def exchange_ghost_rows(self, values: Array, comm_dict: dict) -> Array: + """Refresh the ghost rows of a node feature from their owner ranks. + + Parameters + ---------- + values + Node features with shape ``(N, W)``, the owned rows leading. + comm_dict + Border-exchange tensors of the domain decomposition. + + Returns + ------- + Array + ``values`` with every ghost row replaced by its owner's row. + + Raises + ------ + NotImplementedError + Always in the backend-neutral reference, which runs on one + process. + """ + raise NotImplementedError( + "Multi-rank DPA4C message passing (comm_dict) is not supported in " + "the dpmodel backend." + ) + + def complete_node_partials(self, partials: Array, comm_dict: dict) -> Array: + """Sum per-node partials across ranks and broadcast the totals. + + Parameters + ---------- + partials + Per-node partial sums with shape ``(N, W)``. + comm_dict + Border-exchange tensors of the domain decomposition. + + Returns + ------- + Array + Completed sums on every owned and ghost row. + + Raises + ------ + NotImplementedError + Always in the backend-neutral reference, which runs on one + process. + """ + raise NotImplementedError( + "Multi-rank DPA4C source gating (comm_dict) is not supported in " + "the dpmodel backend." + ) + def gather_rows( self, values: Array, @@ -1361,6 +1698,7 @@ def share_params( "radial_mode_head", "pair_film", "readout", + "attentions", "spin", "charge_spin_embedding", ): @@ -1374,20 +1712,20 @@ def structure_signature(self) -> tuple: The signature compares two live descriptors and is never persisted, so it may reference execution policy as well as persisted structure. - It covers every field that fixes the shape or the meaning - of a shared module. ``rcut``, ``basis_type``, and ``n_radial`` define - the radial basis; ``ntypes`` defines the type table and the ordered - pair index space; ``channels``, ``lmax``, and ``radial_modes`` define - every remaining width; ``use_amp`` selects the precision policy that a - backend attaches to the shared layers, so a replica that autocasts - against layers configured without it would silently lose the effect; - ``trainable`` decides whether - those layers carry gradients at all; ``type_map`` fixes what the rows - of the shared type table mean; ``use_spin`` fixes both the presence - and the row meaning of the shared spin tables; ``add_chg_spin_ebd`` - fixes the presence of the condition module and the width of the pair - encoder head it drives. Precision itself enters through its resolved - dtype so that equivalent spellings agree. + It covers every field that fixes the shape or the meaning of a shared + module. The block cutoffs, ``basis_type``, and ``n_radial`` define the + radial basis and the message-passing blocks; ``ntypes`` defines the type + table and the ordered pair index space; ``channels``, ``lmax``, and + ``radial_modes`` define every remaining width; ``use_amp`` selects the + precision policy that a backend attaches to the shared layers, so a + replica that autocasts against layers configured without it would + silently lose the effect; ``trainable`` decides whether those layers + carry gradients at all; ``type_map`` fixes what the rows of the shared + type table mean; ``use_spin`` fixes both the presence and the row + meaning of the shared spin tables; ``add_chg_spin_ebd`` fixes the + presence of the condition module and the width of the pair encoder head + it drives. Precision itself enters through its resolved dtype so that + equivalent spellings agree. ``default_chg_spin`` is deliberately absent: it is a fallback for a missing input rather than a property of the shared parameters, so two @@ -1404,7 +1742,7 @@ def structure_signature(self) -> tuple: Structural configuration of the shareable modules. """ return ( - self.rcut, + tuple(self.block_rcut), self.ntypes, self.channels, self.lmax, @@ -1482,6 +1820,13 @@ def compute_input_stats( tail is left unchanged. No sample-dependent normalization is evaluated during training or inference. + The measurement runs with the identity calibration, and the attention + of every further block reads the calibrated invariants of the previous + block. It is therefore exact for blocks at their initialization, whose + output maps are zero, so that every block reproduces the moments of + the first; the trainer calibrates a freshly built model, before any + pretrained weights are loaded. + Parameters ---------- merged @@ -1827,8 +2172,11 @@ def serialize(self) -> dict: data = { "@class": "Descriptor", "type": "dpa4c", - "@version": 2, - "rcut": self.rcut, + "@version": 3, + "rcut": ( + self.rcut if len(set(self.block_rcut)) == 1 else list(self.block_rcut) + ), + "n_blocks": self.n_blocks, "ntypes": self.ntypes, "channels": self.channels, "lmax": self.lmax, @@ -1863,6 +2211,7 @@ def serialize(self) -> dict: ), "pair_film": self.pair_film.serialize(), "readout": self.readout.serialize(), + "attentions": [attention.serialize() for attention in self.attentions], "@variables": { "mean": to_numpy_array(self.mean), "stddev": to_numpy_array(self.stddev), @@ -1892,9 +2241,11 @@ def deserialize(cls, data: dict) -> DescrptDPA4C: Reconstructed descriptor with restored trainable components. """ data = data.copy() - check_version_compatibility(data.pop("@version"), 2, 1) + check_version_compatibility(data.pop("@version"), 3, 1) data.pop("@class") data.pop("type") + # Records of format 2 and earlier hold one block. + data.setdefault("n_blocks", 1) compression = data.pop("compress", None) variables = data.pop("@variables") type_embedding = data.pop("type_embedding") @@ -1903,6 +2254,8 @@ def deserialize(cls, data: dict) -> DescrptDPA4C: radial_mode_head = data.pop("radial_mode_head") pair_film = data.pop("pair_film") readout = data.pop("readout") + # Records of format 2 and earlier carry one cutoff and one block. + attentions = data.pop("attentions", []) spin_channels = data.pop("spin_channels") charge_spin_embedding = data.pop("charge_spin_embedding") @@ -1917,6 +2270,13 @@ def deserialize(cls, data: dict) -> DescrptDPA4C: ) obj.pair_film = OrderedPairFiLM.deserialize(pair_film) obj.readout = InvariantReadout.deserialize(readout) + if len(attentions) != len(obj.attentions): + raise ValueError( + f"Serialized descriptor holds {len(attentions)} further " + f"blocks, but `n_blocks` = {len(obj.attentions) + 1} needs " + f"{len(obj.attentions)}." + ) + obj.attentions = [BlockAttention.deserialize(record) for record in attentions] obj.spin = ( None if spin_channels is None else SpinChannels.deserialize(spin_channels) ) @@ -2092,10 +2452,11 @@ def has_message_passing(self) -> bool: """Return whether source-node features are exchanged. The spin branch reads the raw source spin, which is a node input - rather than a derived feature, so a spin-conditioned descriptor - remains message-passing free. + rather than a derived feature, so a single-block descriptor remains + message-passing free. Every further block reads derived features of + the edge source. """ - return False + return bool(self.attentions) def supports_native_spin(self) -> bool: """Return whether ``call_graph`` conditions on a per-node spin.""" @@ -2135,6 +2496,10 @@ def get_default_chg_spin(self) -> list[float] | None: def has_message_passing_across_ranks(self) -> bool: """Return whether intermediate halo communication is required.""" + return bool(self.attentions) + + def dense_lower_supports_comm(self) -> bool: + """Cross-rank feature exchange is implemented only by the graph lower.""" return False def need_sorted_nlist_for_lower(self) -> bool: diff --git a/deepmd/dpmodel/descriptor/dpa4c_nn/__init__.py b/deepmd/dpmodel/descriptor/dpa4c_nn/__init__.py index 8bd43d4cc0..0ad9df1dab 100644 --- a/deepmd/dpmodel/descriptor/dpa4c_nn/__init__.py +++ b/deepmd/dpmodel/descriptor/dpa4c_nn/__init__.py @@ -1,6 +1,9 @@ # SPDX-License-Identifier: LGPL-3.0-or-later """Neural and geometric building blocks for DPA4C.""" +from .attention import ( + BlockAttention, +) from .bispectrum import ( BispectrumLayout, build_bispectrum_layout, @@ -34,6 +37,7 @@ "MAX_ANGULAR_DEGREE", "NEIGHBOR_QUADRUPOLE_CHANNELS", "BispectrumLayout", + "BlockAttention", "ChargeStateEmbedding", "InvariantReadout", "OrderedPairFiLM", diff --git a/deepmd/dpmodel/descriptor/dpa4c_nn/attention.py b/deepmd/dpmodel/descriptor/dpa4c_nn/attention.py new file mode 100644 index 0000000000..dc1ec0bc2e --- /dev/null +++ b/deepmd/dpmodel/descriptor/dpa4c_nn/attention.py @@ -0,0 +1,513 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Attention of the further DPA4C message-passing blocks.""" + +from __future__ import ( + annotations, +) + +import itertools +from typing import ( + Any, +) + +import array_api_compat +import numpy as np + +from deepmd.dpmodel import ( + DEFAULT_PRECISION, + PRECISION_DICT, + NativeOP, +) +from deepmd.dpmodel.array_api import ( + xp_asarray_nodetach, + xp_sigmoid, +) +from deepmd.dpmodel.common import ( + to_numpy_array, +) +from deepmd.dpmodel.utils.neighbor_graph import ( + segment_sum, +) +from deepmd.dpmodel.utils.network import ( + NativeLayer, + softplus_t, +) +from deepmd.dpmodel.utils.seed import ( + child_seed, +) +from deepmd.utils.version import ( + check_version_compatibility, +) + +from ..dpa4_nn.mlp import ( + SwiGLUMLP, +) +from .geometry import ( + degree_offsets, +) + +#: Single sub-layers of a block, serialized by name. +_SINGLE_LAYERS = ( + "hidden_state", + "hidden_field", + "hidden_amplitude", + "hidden_output", + "transport_radial", + "null_mass", +) +#: Per-degree sub-layer lists of a block, serialized by name. +_LAYER_LISTS = ("key_projections", "transport_outputs") + + +def soft_saturate(value: Any, knee: float) -> Any: + r"""Map every entry through :math:`x/\sqrt{1+(x/x_0)^2}`. + + The map is the identity to first order and bounds its output by the knee + :math:`x_0`; its slope decays as :math:`|x|^{-3}` far beyond it. + """ + xp = array_api_compat.array_namespace(value) + scale = xp.maximum( + xp.abs(value), + xp.asarray(knee, dtype=value.dtype, device=array_api_compat.device(value)), + ) + scaled_value = value / scale + scaled_knee = knee / scale + return ( + knee + * scaled_value + / xp.sqrt(scaled_value * scaled_value + scaled_knee * scaled_knee) + ) + + +class BlockAttention(NativeOP): + r"""Attention of one further message-passing block. + + Block :math:`k` reads the moments :math:`X^{(k-1)}` and the calibrated + invariants :math:`D^{(k-1)}` of the previous block. Every node carries + saturated equivariant keys, one per head :math:`h` and non-scalar degree, + + .. math:: + + K_{jh}^{(\ell)}=X_j^{(\ell)}A_h^{(\ell)}\Big/ + \sqrt{1+|X_j^{(\ell)}A_h^{(\ell)}|^2/\kappa^2}, + + and every edge :math:`j\to i` reads the fields of its source along the + bond towards the center, :math:`F_{ij\ell h}=B^{(\ell)}(\hat u_{ji})\cdot + K_{jh}^{(\ell)}`, which measure how the environment of the neighbor is + oriented relative to the bond. The logit of amplitude channel :math:`c` + sums three terms of the neighbor, + + .. math:: + + a_{ijc}=\sum_\ell g_{\ell h}F_{ij\ell h}+s_{jc} + +\bigl[\mathrm{SiLU}\bigl(W_D\tilde D_j+W_FF_{ij} + +W_\phi\tilde\phi_{ij}\bigr)W_O\bigr]_c,\qquad h=c\bmod H: + + a field per head, the encoded state :math:`s_j` of its saturated + invariants :math:`\tilde D_j`, and a hidden layer that reads the state, + every field and the saturated first-block amplitude + :math:`\tilde\phi_{ij}` together. The hidden layer lets the effect of the + neighbor on a channel depend on the distance and the type pair of the + edge, which a factor of the neighbor alone cannot express. Every + first-block amplitude is rescaled by + :math:`m_{ijc}=1+\chi_k(r_{ij})\tanh a_{ijc}`, which lies in + :math:`(0,2)`, so a neighbor reweights its message but cannot invert it. + + The keys of the neighbors also enter the non-scalar moments of the + center, which receive the directions of the second shell through an + envelope-weighted softmax of the capped logits of the leading :math:`H` + channels with a null mass :math:`\zeta_{ih}` that the center sets: + + .. math:: + + \Delta X_i^{(\ell)}=\sum_h\frac{\sum_j\mu_{ijh}\rho_{ijh}K_{jh}^{(\ell)}} + {\zeta_{ih}+\sum_j\mu_{ijh}}O_h^{(\ell)},\qquad + \mu_{ijh}=\chi_k^2\chi_{ij}^2e^{c\tanh(a_{ijh}/c)}, + + with a radial weight :math:`\rho_{ijh}` of the saturated amplitude. Every + learned map reads saturated inputs, so close contacts, which drive the + moments, the invariants and the amplitude far outside the sampled range, + cannot drive the maps outside the range they were trained on. + + Every output map starts at zero, so a block starts as the identity, and + every term vanishes with the C³ envelope :math:`\chi_k` of the block at + its cutoff. Under zone bridging the first-block envelope :math:`\chi_{ij}` + carries the source gate, which removes a frozen atom from the numerator + and the denominator of the softmax alike. Source features are formed per + node by :meth:`source_features` and center features by + :meth:`center_features`; a distributed caller refreshes the ghost rows of + the source features in between. + + Parameters + ---------- + degree_channels + Channel widths of degrees zero through ``lmax``. + descriptor_dim + Width of the calibrated invariants that the encoders read. + precision + Parameter precision. + trainable + Whether the parameters are trainable. + seed + Random seed reserved for the block. + """ + + #: Number :math:`H` of heads, each with its own keys, field gains and + #: softmax; amplitude channel :math:`c` follows head :math:`c \bmod H`. + HEADS = 2 + #: Hidden width of the state encoder. + STATE_WIDTH = 16 + #: Knee of the saturation of the calibrated invariants. + STATE_KNEE = 2.0 + #: Knee :math:`\kappa` of the saturation of the keys. + KEY_KNEE = 1.5 + #: Knee of the saturation of the amplitude that the learned maps read. + AMPLITUDE_KNEE = 1.5 + #: Cap :math:`c` of the softmax logit. + LOGIT_CAP = 2.0 + #: Floor of the null mass of the softmax. + NULL_FLOOR = 1.0e-6 + #: Sign tables that the constructor rebuilds from the configuration, kept + #: out of the state dictionary. + CONFIG_DERIVED_ARRAYS = ("head_index", "reflection_sign") + + def __init__( + self, + degree_channels: list[int], + descriptor_dim: int, + *, + precision: str = DEFAULT_PRECISION, + trainable: bool = True, + seed: int | list[int] | None = None, + ) -> None: + self.degree_channels = [int(width) for width in degree_channels] + self.descriptor_dim = int(descriptor_dim) + self.precision = str(precision) + self.trainable = bool(trainable) + self.degree_offsets = degree_offsets(self.degree_channels) + dtype = PRECISION_DICT[self.precision] + channels = self.degree_channels[0] + n_degree = len(self.degree_channels) - 1 + heads = self.HEADS + seeds = itertools.count() + + def layer(n_in: int, n_out: int, zero: bool) -> NativeLayer: + built = NativeLayer( + n_in, + n_out, + bias=False, + precision=self.precision, + trainable=self.trainable, + seed=child_seed(seed, next(seeds)), + ) + if zero: + built.w = np.zeros((n_in, n_out), dtype=dtype) + return built + + # === Step 1. Keys with orthonormal columns where the width allows === + self.key_projections = [] + for degree in range(1, n_degree + 1): + width = self.degree_channels[degree] + projection = layer(width, heads, zero=False) + draw = np.random.default_rng(child_seed(seed, next(seeds))).normal( + size=(width, heads) + ) + if width >= heads: + draw = np.linalg.qr(draw)[0] + else: + draw /= np.linalg.norm(draw, axis=0, keepdims=True) + projection.w = draw.astype(dtype) + self.key_projections.append(projection) + + # === Step 2. Logit terms of the neighbor === + self.adam_field_gain = np.zeros((n_degree, heads), dtype=dtype) + self.state_encoder = SwiGLUMLP( + [self.descriptor_dim, self.STATE_WIDTH, channels], + precision=self.precision, + trainable=self.trainable, + seed=child_seed(seed, next(seeds)), + ) + self.state_encoder.layers[-1].w = np.zeros( + (self.STATE_WIDTH, channels), dtype=dtype + ) + self.hidden_state = layer(self.descriptor_dim, channels, zero=False) + self.hidden_field = layer(n_degree * heads, channels, zero=False) + self.hidden_amplitude = layer(channels, channels, zero=False) + self.hidden_output = layer(channels, channels, zero=True) + + # === Step 3. Transport of the neighbor keys === + self.transport_radial = layer(channels, heads, zero=False) + self.transport_outputs = [ + layer(heads, self.degree_channels[degree], zero=True) + for degree in range(1, n_degree + 1) + ] + self.null_mass = NativeLayer( + self.descriptor_dim, + heads, + bias=True, + precision=self.precision, + trainable=self.trainable, + seed=child_seed(seed, next(seeds)), + ) + self.null_mass.w = np.zeros((self.descriptor_dim, heads), dtype=dtype) + # softplus(0.5413) = 1 gives the null the mass of one full edge. + self.null_mass.b = np.full(heads, 0.5413, dtype=dtype) + + # === Step 4. Head assignment and reflection signs === + # Amplitude channel c follows head c mod H. The fields read the bond + # towards the center, and B_l(-u) = (-1)^l B_l(u). + self.head_index = np.arange(channels, dtype=np.int64) % heads + self.reflection_sign = np.concatenate( + [ + np.full(2 * degree + 1, (-1.0) ** degree, dtype=dtype) + for degree in range(1, n_degree + 1) + ] + ) + + @property + def harmonic_width(self) -> int: + """Return the number of non-scalar harmonic components ``(L + 1)^2 - 1``.""" + return len(self.degree_channels) ** 2 - 1 + + @property + def key_width(self) -> int: + """Return the width of the keys in the source features.""" + return self.harmonic_width * self.HEADS + + # === Node features === + + def source_features(self, moments: Any, invariants: Any) -> Any: + """Build the per-node features that every edge reads from its source. + + Parameters + ---------- + moments + Normalized moments of the previous block with shape ``(N, S)``; + columns past the geometric degrees are not read. + invariants + Calibrated invariants of the previous block with shape + ``(N, descriptor_dim)``. + + Returns + ------- + Any + Source features with shape ``(N, key_width + 2 * C_0)``: the keys, + harmonic-major with the heads innermost, the state and the + neighbor term of the hidden layer. + """ + xp = array_api_compat.array_namespace(moments) + n_node = moments.shape[0] + blocks = [] + for degree, projection in enumerate(self.key_projections, start=1): + start, end = self.degree_offsets[degree : degree + 2] + block = projection.call( + xp.reshape( + moments[:, start:end], + (n_node, 2 * degree + 1, self.degree_channels[degree]), + ) + ) + # The saturation acts on the norm of every head, which keeps its + # direction and therefore its transformation law. + norm_squared = xp.sum(block * block, axis=1, keepdims=True) + blocks.append( + block / xp.sqrt(1.0 + norm_squared / (self.KEY_KNEE * self.KEY_KNEE)) + ) + keys = xp.reshape(xp.concat(blocks, axis=1), (n_node, self.key_width)) + saturated = soft_saturate(invariants, self.STATE_KNEE) + return xp.concat( + [ + keys, + self.state_encoder.call(saturated), + self.hidden_state.call(saturated), + ], + axis=1, + ) + + def center_features(self, invariants: Any) -> Any: + """Return the null-mass logits of every center with shape ``(N, H)``.""" + return self.null_mass.call(soft_saturate(invariants, self.STATE_KNEE)) + + # === Edge evaluation === + + def call( + self, + sources: Any, + centers: Any, + amplitude: Any, + basis: Any, + envelope: Any, + block_envelope: Any, + src: Any, + dst: Any, + ) -> tuple[Any, Any]: + """Evaluate the rescaled amplitudes and the transported moments. + + Parameters + ---------- + sources + Source features of every node with shape ``(N, key_width + 2 * C_0)``. + centers + Center features of every node with shape ``(N, H)``. + amplitude + Enveloped first-block edge amplitudes with shape ``(E, C_0)``. + basis + Cartesian harmonics of the edge directions with shape + ``(E, (lmax + 1) ** 2)``. + envelope + Masked C³ envelope of the first block with shape ``(E,)``, + including the bridging switch and the source gate. + block_envelope + C³ envelope at the cutoff of this block with shape ``(E,)``. + src, dst + Source and destination node of every edge with shape ``(E,)``. + + Returns + ------- + amplitude + Edge amplitudes of this block with shape ``(E, C_0)``. + transport + Transported non-scalar moments with shape ``(N, S_geo - C_0)``. + """ + xp = array_api_compat.array_namespace(sources) + device = array_api_compat.device(sources) + heads = self.HEADS + channels = self.degree_channels[0] + # Each part of the source features is gathered on its own, so every + # backward scatters narrow cotangents instead of one zero-padded row + # of the full width. + n_edge = src.shape[0] + key_end = self.key_width + state_end = key_end + channels + keys = xp.reshape( + xp.take(sources[:, :key_end], src, axis=0), + (n_edge, self.harmonic_width, heads), + ) + state = xp.take(sources[:, key_end:state_end], src, axis=0) + hidden = xp.take(sources[:, state_end:], src, axis=0) + saturated = soft_saturate(amplitude, self.AMPLITUDE_KNEE) + + # === Step 1. Fields of the neighbor along the reversed bond === + sign = xp_asarray_nodetach(xp, self.reflection_sign, device=device) + signed = (basis[:, 1:] * sign)[:, :, None] * keys + fields = [] + start = 0 + for degree in range(1, len(self.degree_channels)): + size = 2 * degree + 1 + fields.append(xp.sum(signed[:, start : start + size, :], axis=1)) + start += size + fields = xp.stack(fields, axis=1) # (E, L, H) + + # === Step 2. Logit of every amplitude channel === + gain = xp_asarray_nodetach(xp, self.adam_field_gain, device=device) + head_index = xp_asarray_nodetach(xp, self.head_index, device=device) + flat_fields = xp.reshape( + fields, (n_edge, (len(self.degree_channels) - 1) * heads) + ) + hidden = ( + hidden + + self.hidden_field.call(flat_fields) + + self.hidden_amplitude.call(saturated) + ) + logit = ( + xp.take(xp.sum(fields * gain[None], axis=1), head_index, axis=1) + + state + + self.hidden_output.call(hidden * xp_sigmoid(hidden)) + ) + rescaled = amplitude * (1.0 + block_envelope[:, None] * xp.tanh(logit)) + + # === Step 3. Softmax transport of the neighbor keys === + n_node = sources.shape[0] + weight = envelope * block_envelope + capped = self.LOGIT_CAP * xp.tanh(logit[:, :heads] / self.LOGIT_CAP) + mass = (weight * weight)[:, None] * xp.exp(capped) # (E, H) + denominator = ( + segment_sum(mass, dst, n_node) + softplus_t(centers) + self.NULL_FLOOR + ) + weighted = (mass * self.transport_radial.call(saturated))[:, None, :] * keys + reduced = segment_sum( + xp.reshape(weighted, (n_edge, self.key_width)), dst, n_node + ) + reduced = ( + xp.reshape(reduced, (n_node, self.harmonic_width, heads)) + / denominator[:, None, :] + ) + transported = [] + start = 0 + for degree, output in enumerate(self.transport_outputs, start=1): + size = 2 * degree + 1 + transported.append( + xp.reshape( + output.call(reduced[:, start : start + size, :]), + (n_node, size * self.degree_channels[degree]), + ) + ) + start += size + return rescaled, xp.concat(transported, axis=1) + + def serialize(self) -> dict[str, Any]: + """Serialize the block attention. + + Returns + ------- + dict[str, Any] + Versioned configuration and parameters. + """ + layers: dict[str, Any] = { + name: [layer.serialize() for layer in getattr(self, name)] + for name in _LAYER_LISTS + } + for name in _SINGLE_LAYERS: + layers[name] = getattr(self, name).serialize() + layers["state_encoder"] = self.state_encoder.serialize() + return { + "@class": "BlockAttention", + "@version": 1, + "degree_channels": list(self.degree_channels), + "descriptor_dim": self.descriptor_dim, + "precision": self.precision, + "trainable": self.trainable, + "layers": layers, + "@variables": {"adam_field_gain": to_numpy_array(self.adam_field_gain)}, + } + + @classmethod + def deserialize(cls, data: dict[str, Any]) -> BlockAttention: + """Deserialize a :class:`BlockAttention`. + + Parameters + ---------- + data + Versioned dictionary produced by :meth:`serialize`. + + Returns + ------- + BlockAttention + Reconstructed block with restored parameters. + + Raises + ------ + ValueError + If the payload does not describe a :class:`BlockAttention`. + """ + data = data.copy() + check_version_compatibility(data.pop("@version"), 1, 1) + if data.pop("@class") != "BlockAttention": + raise ValueError("Invalid serialized class for BlockAttention") + layers = data.pop("layers") + variables = data.pop("@variables") + obj = cls(**data) + for name in _LAYER_LISTS: + records = layers[name] + if len(records) != len(getattr(obj, name)): + raise ValueError( + f"Serialized `{name}` holds {len(records)} layers, expected " + f"{len(getattr(obj, name))}." + ) + setattr(obj, name, [NativeLayer.deserialize(record) for record in records]) + for name in _SINGLE_LAYERS: + setattr(obj, name, NativeLayer.deserialize(layers[name])) + obj.state_encoder = SwiGLUMLP.deserialize(layers["state_encoder"]) + obj.adam_field_gain = np.asarray( + variables["adam_field_gain"], dtype=PRECISION_DICT[obj.precision] + ) + return obj diff --git a/deepmd/dpmodel/utils/lmdb_data.py b/deepmd/dpmodel/utils/lmdb_data.py index f5e39a98ac..e4e5c1b33f 100644 --- a/deepmd/dpmodel/utils/lmdb_data.py +++ b/deepmd/dpmodel/utils/lmdb_data.py @@ -118,7 +118,7 @@ # authoritative ``atomic`` flag; these two sets cover the fields that exist # without one. _STRUCTURAL_PER_ATOM_KEYS = frozenset({"coord", "atype"}) -_OPTIONAL_PER_ATOM_KEYS = frozenset({"aparam", "spin"}) +_OPTIONAL_PER_ATOM_KEYS = frozenset({"aparam", "force", "spin"}) # Frame-level fields that a decoded frame may carry without a registered # requirement. They anchor the shape-based fallback below, which classifies any @@ -2676,9 +2676,12 @@ def use_ragged_batches(self, ragged: bool) -> None: def per_atom_strides(self, index: int = 0) -> dict[str, int]: """Return the leading-axis entries per atom of each per-atom field. - Every frame of one LMDB exposes the same fields, so the classification - is a property of the dataset and its registered requirements rather - than of a batch, and is resolved from a selected frame once. + Registered fields determine their atom axis. For an undeclared field, + the leading axis is compared with the atom count on the selected frame + and on a representative record of every other atom-count group that + carries it. Missing optional fields do not settle the classification. + These probes read raw field shapes, without validating, transforming, + or deriving labels in records outside the selected batch. Parameters ---------- @@ -2693,9 +2696,38 @@ def per_atom_strides(self, index: int = 0) -> dict[str, int]: """ if self._per_atom_strides is None: frame = self[index] - self._per_atom_strides = per_atom_strides( - frame, resolve_per_atom_keys(frame, self._decode_config) + keys = set(resolve_per_atom_keys(frame, self._decode_config)) + inferred = keys - ( + _STRUCTURAL_PER_ATOM_KEYS + | _OPTIONAL_PER_ATOM_KEYS + | self._decode_config.data_requirements.keys() ) + for nloc, indices in self._nloc_groups.items(): + if nloc == self._frame_nlocs[index] or not inferred: + continue + pending = inferred.copy() + for other in indices: + key = format( + int(self._retained_keys[other]), self._frame_fmt + ).encode() + raw = self._transaction().get(key) + if raw is None: + raise IndexError(f"Frame {key.decode()} not found in LMDB") + record = _remap_keys(_decode_frame(raw, copy_arrays=False)) + present = pending & record.keys() + for field in present: + value = record[field] + if not ( + isinstance(value, np.ndarray) + and value.ndim >= 1 + and value.shape[0] == nloc + ): + keys.remove(field) + inferred.remove(field) + pending -= present + if not pending: + break + self._per_atom_strides = per_atom_strides(frame, keys) return self._per_atom_strides def decode_batch( diff --git a/deepmd/pt/utils/compile_compat.py b/deepmd/pt/utils/compile_compat.py index 6f8c349cea..e2ac74530e 100644 --- a/deepmd/pt/utils/compile_compat.py +++ b/deepmd/pt/utils/compile_compat.py @@ -648,11 +648,11 @@ def build_inductor_compile_options(*, inference: bool = False) -> dict[str, Any] if tune_train >= 2: compile_options["max_autotune_gemm"] = True if inference: - # PyTorch 2.11 CPU horizontal fusion can reuse a scatter's index - # array in an earlier gather, before the array is declared. Keep - # those loops separate while retaining SIMD and vertical fusion. + # PyTorch 2.11 CPU SIMD codegen can reuse a scatter's index array + # in an earlier gather before its declaration, even without + # horizontal fusion. Scalar codegen preserves the dynamic graph. if _torch_release() == (2, 11): - compile_options["cpp.max_horizontal_fusion_size"] = 1 + compile_options["cpp.simdlen"] = 1 # The peak-memory reordering pass sizes buffers through # ``sizevars.size_hint(numel, fallback=0)``. The inference graph is # lowered from ``make_fx`` fake placeholders whose edge-count symbols diff --git a/deepmd/pt_expt/descriptor/dpa4c.py b/deepmd/pt_expt/descriptor/dpa4c.py index 4707313829..477ca84b9f 100644 --- a/deepmd/pt_expt/descriptor/dpa4c.py +++ b/deepmd/pt_expt/descriptor/dpa4c.py @@ -46,6 +46,7 @@ "adam_spin_quadrupole_weight", "spin_gate", ), + "BlockAttention": ("adam_field_gain",), } @@ -211,7 +212,8 @@ def call_graph( type_embedding Optional complete DPA4 type table. comm_dict - Communication metadata accepted by the common graph ABI; unused. + Border-exchange tensors of a domain-decomposed graph, read by + every further message-passing block. spin Per-node spin with shape ``(N, 3)``, mandatory for a spin-conditioned descriptor. @@ -238,11 +240,11 @@ def call_graph( ): from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( dpa4c_graph_compress, - mega_eligible, + graph_operator_eligible, op_available, ) - if op_available(self.spin is not None) and mega_eligible(self): + if op_available(self.spin is not None) and graph_operator_eligible(self): # The operator conditions the moment on device from its frozen # per-type table, so it takes the raw input rather than the # output of ``SpinChannels.conditioned_spin``. @@ -263,6 +265,17 @@ def call_graph( charge_spin=charge_spin, ) + def require_charge_spin( + self, + charge_spin: torch.Tensor | None, + nf: int, + ref: torch.Tensor, + ) -> torch.Tensor | None: + """Resolve the snapshot state for graph and dense reference paths.""" + return super().require_charge_spin( + None if self.compress else charge_spin, nf, ref + ) + def build_edge_features( self, graph: Any, @@ -302,8 +315,9 @@ def build_edge_features( graph Neighbor graph in descriptor compute precision. *args - Node types, the ordered pair cache, and the conditioned spin, - forwarded unchanged to the backend-neutral implementation. + Node types, the ordered pair cache, the conditioned spin, and the + border-exchange tensors, forwarded unchanged to the + backend-neutral implementation. Returns ------- @@ -348,6 +362,78 @@ def _apply_autocast_policy(self) -> None: # === Backend primitives === + def exchange_ghost_rows( + self, values: torch.Tensor, comm_dict: dict[str, torch.Tensor] + ) -> torch.Tensor: + """Refresh the ghost rows of a node feature through ``border_op``. + + The copy from owner to ghost is exact: a ghost is a translated image of + its owner, every rank describes the equivariant features in the same + Cartesian frame, and a translation leaves them unchanged. + ``border_op`` has a registered backward, which reverse-communicates the + cotangent of the ghost rows to their owners. + + Parameters + ---------- + values + Node features with shape ``(N, W)``, the owned rows leading. + comm_dict + Border-exchange tensors of the domain decomposition. + + Returns + ------- + torch.Tensor + ``values`` with every ghost row replaced by its owner's row. + """ + # border_op exchanges whole rows by raw pointer arithmetic, so the + # buffer must be contiguous. + return torch.ops.deepmd_export.border_op( + comm_dict["send_list"], + comm_dict["send_proc"], + comm_dict["recv_proc"], + comm_dict["send_num"], + comm_dict["recv_num"], + values.contiguous(), + comm_dict["communicator"], + comm_dict["nlocal"], + comm_dict["nghost"], + ) + + def complete_node_partials( + self, partials: torch.Tensor, comm_dict: dict[str, torch.Tensor] + ) -> torch.Tensor: + """Sum ghost partials into their owners, then broadcast the totals back. + + ``border_op_backward`` accumulates each ghost row into its owner + across ranks; ``border_op`` refills the ghost rows with the completed + owner values. The two ops are transposes of one another and both + carry autograd, so the gradient of the source gate crosses ranks. + + Parameters + ---------- + partials + Per-node partial sums with shape ``(N, W)``. + comm_dict + Border-exchange tensors of the domain decomposition. + + Returns + ------- + torch.Tensor + Completed sums on every owned and ghost row. + """ + arguments = ( + comm_dict["send_list"], + comm_dict["send_proc"], + comm_dict["recv_proc"], + comm_dict["send_num"], + comm_dict["recv_num"], + ) + tail = (comm_dict["communicator"], comm_dict["nlocal"], comm_dict["nghost"]) + completed = torch.ops.deepmd_export.border_op_backward( + *arguments, partials.contiguous(), *tail + ) + return torch.ops.deepmd_export.border_op(*arguments, completed, *tail) + def gather_rows( self, values: torch.Tensor, @@ -592,8 +678,12 @@ def apply_charge_state(self, charge_spin: Any) -> None: from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( build_charge_state_artifacts, ) + from deepmd.utils.charge_state import ( + validate_charge_state, + ) - artifacts = build_charge_state_artifacts(self, charge_spin) + state = validate_charge_state(charge_spin) + artifacts = build_charge_state_artifacts(self, state) device = self.compress_pair_film.device for name, value in artifacts.items(): self._buffers[f"compress_{name}"] = value.to( @@ -601,6 +691,8 @@ def apply_charge_state(self, charge_spin: Any) -> None: dtype=torch.float32, ).contiguous() + self.default_chg_spin = state + def set_stat_mean_and_stddev(self, mean: Any, stddev: Any) -> None: """Update output calibration and its compressed snapshot.""" super().set_stat_mean_and_stddev(mean, stddev) @@ -731,7 +823,7 @@ def fused_energy_force_graph( from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( dpa4c_graph_compress_energy_force, ef_op_available, - mega_eligible, + graph_operator_eligible, ) from deepmd.pt_expt.kernels.graph_fitting import ( fitting_eligible, @@ -739,7 +831,7 @@ def fused_energy_force_graph( if ( not ef_op_available(self.spin is not None) - or not mega_eligible(self) + or not graph_operator_eligible(self) or not fitting_eligible(fitting) ): return None diff --git a/deepmd/pt_expt/infer/charge_state.py b/deepmd/pt_expt/infer/charge_state.py index d6bcb68758..97518d3819 100644 --- a/deepmd/pt_expt/infer/charge_state.py +++ b/deepmd/pt_expt/infer/charge_state.py @@ -152,9 +152,10 @@ class ChargeStateFold: Every lower lifts its constants independently, so the names hold only for the lower they were resolved against at freeze time. Only a compressed - DPA4C descriptor folds a charge state, and that family never carries - message passing across ranks, so an archive with a fold holds exactly one - lower and the question of a second set of names does not arise. + DPA4C descriptor folds a charge state. Its single-block graph lower needs + no with-comm artifact, and its multi-block compressed canonical lower + carries halo exchange in the main ABI. An archive with a fold therefore + holds one inference lower and one set of constant names. Parameters ---------- diff --git a/deepmd/pt_expt/infer/deep_eval.py b/deepmd/pt_expt/infer/deep_eval.py index a211da928a..43fd0e3e99 100644 --- a/deepmd/pt_expt/infer/deep_eval.py +++ b/deepmd/pt_expt/infer/deep_eval.py @@ -1139,20 +1139,6 @@ def _folded_charge_state( charge_spin = self.metadata["default_chg_spin"] return single_charge_state(charge_spin, fold.width) - @property - def _dpmodel_dim_chg_spin(self) -> int: - """Width of the condition the deserialized model reads as an argument. - - An archive that ships its model dict is deserialized into an ordinary - implementation beside the compiled lower, and the introspection - methods evaluate that one. It reads the condition as an argument even - where the lower reads none, so the two widths part company exactly - when a fold exists, and the fold carries the width. - """ - if self._charge_state_fold is not None: - return self._charge_state_fold.width - return self.get_dim_chg_spin() - def _make_charge_spin_input( self, nframes: int, charge_spin: np.ndarray | None = None ) -> torch.Tensor | None: @@ -1192,12 +1178,11 @@ def _make_charge_spin_input( def _make_dpmodel_charge_spin_input( self, nframes: int, charge_spin: np.ndarray | None = None ) -> torch.Tensor | None: - """Build the condition the deserialized model reads. + """Serve the condition to the deserialized model used for introspection. - The introspection methods evaluate that model rather than the compiled - lower, so they condition it through this argument; folding the state - into the compressed tables would not reach them, as those tables are - read only by the fused kernel behind the lower. + A compressed descriptor reads its stored state and folded tables, + whereas an uncompressed descriptor reads a runtime tensor. All + introspection routes use this boundary to select the requested state. Parameters ---------- @@ -1213,8 +1198,9 @@ def _make_dpmodel_charge_spin_input( The condition with shape ``(nframes, dim_chg_spin)``, or ``None`` for a model that carries no charge/spin conditioning. """ + self._apply_dpmodel_charge_state(charge_spin) return self._charge_spin_tensor( - nframes, charge_spin, self._dpmodel_dim_chg_spin + nframes, charge_spin, self._dpmodel.get_dim_chg_spin() ) def _charge_spin_tensor( @@ -2358,7 +2344,9 @@ def _prepare_graph_inputs( ) -> tuple[tuple[torch.Tensor | None, ...], int, int]: """Pack local graph inputs according to the exported artifact's ABI.""" from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, canonical_index_bytes, + validate_reciprocal_canonical_graph, ) from deepmd.pt_expt.utils.env import ( DEVICE, @@ -2372,6 +2360,10 @@ def _prepare_graph_inputs( coords, cells, atom_types, canonical=canonical ) if canonical: + if self.metadata.get( + "lower_input_kind" + ) == "dpa4c_canonical" and self.metadata.get("has_message_passing", False): + validate_reciprocal_canonical_graph(graph) # The compact ABI has no conditional input slots. Compressed charge # conditioning instead updates the constants through its fold. if ( @@ -2444,6 +2436,18 @@ def _prepare_graph_inputs( DEVICE, ), ) + if canonical and self.metadata.get("has_message_passing", False): + # Frames held whole carry no halo nodes, so the border plan of a + # model with further message-passing blocks has no swaps. The + # inputs of a long-range module, which the compact lower reads + # first, hold the communicator already. + border = BorderPlan.single_domain(DEVICE) + model_inputs = ( + *model_inputs, + *(() if topology_names else (border.communicator,)), + border.send_nodes, + border.swaps, + ) return model_inputs, nframes, natoms def _long_range_inputs( @@ -2534,6 +2538,12 @@ def _build_eval_graph( compact canonical layout directly when ``canonical`` asks for it and no pair exclusions are needed. """ + # A caller may pass broadcast views, whose zero strides survive the + # zero-copy conversion to torch; the Warp neighbor search on the + # device rejects arrays whose inner strides are not contiguous. + coord_input = np.ascontiguousarray(coord_input) + if box_input is not None: + box_input = np.ascontiguousarray(box_input) method = self._neighbor_graph_method if method == "auto": coord_arr = np.asarray(coord_input) @@ -2898,9 +2908,8 @@ def eval_descriptor( ) = self._prepare_nlist_inputs( coords, cells, atom_types, fparam, aparam, charge_spin ) - # The lower's condition is not the one this path reads: it evaluates - # the deserialized model, which takes the condition as an argument - # even where the lower has it folded into constants. + # The deserialized descriptor owns its conditioning state separately + # from the compiled lower prepared above. charge_spin_t = self._make_dpmodel_charge_spin_input(nframes, charge_spin) with torch.no_grad(): descriptor, *_ = dp_am.descriptor( @@ -2975,9 +2984,8 @@ def eval_fitting_last_layer( ) = self._prepare_nlist_inputs( coords, cells, atom_types, fparam, aparam, charge_spin ) - # The lower's condition is not the one this path reads: it evaluates - # the deserialized model, which takes the condition as an argument - # even where the lower has it folded into constants. + # The deserialized descriptor owns its conditioning state separately + # from the compiled lower prepared above. charge_spin_t = self._make_dpmodel_charge_spin_input(nframes, charge_spin) with torch.no_grad(): descriptor, rot_mat, g2, h2, _sw = dp_am.descriptor( @@ -3086,9 +3094,8 @@ def eval_embedding( natoms, numb_test = self._get_natoms_and_nframes( coords, atom_types, len(atom_types.shape) > 1 ) - # The folded tables of a compressed model hold one condition at a - # time, which every frame of the call therefore shares. - self._apply_dpmodel_charge_state(charge_spin) + # Validate the whole request before batching can split distinct states. + self._folded_charge_state(charge_spin) return self._eval_func(self._eval_embedding, numb_test, natoms)( coords, cells, atom_types, fparam, aparam, charge_spin, dtype ) diff --git a/deepmd/pt_expt/kernels/dpa4c/attention.py b/deepmd/pt_expt/kernels/dpa4c/attention.py new file mode 100644 index 0000000000..f1fd6d9476 --- /dev/null +++ b/deepmd/pt_expt/kernels/dpa4c/attention.py @@ -0,0 +1,591 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +r"""Compressed artifacts and portable equations of the further DPA4C blocks. + +A block after the first (:class:`~deepmd.dpmodel.descriptor.dpa4c_nn.BlockAttention`) +reads features of the edge sources, so none of its maps is a function of the +pair distance alone that a radial table could hold. Compression therefore +packs the weights of every further block into one fp32 record in the layout +the compiled operator reads, and the operator evaluates each block exactly. + +Block :math:`k` corrects the moments of the first block over the edges inside +its own cutoff. With the attention factor :math:`m=1+t`, +:math:`t_{ijc}=\chi_k(r_{ij})\tanh a_{ijc}`, which vanishes with the envelope +of the block, + +.. math:: + + X^{(0),k}_i=X^{(0),1}_i+\frac{1}{d^{(0)}_i}\sum_j\phi_{ij}t_{ij},\qquad + X^{(\ell),k}_i=X^{(\ell),1}_i+\frac{1}{d^{(+)}_i} + \sum_j\chi_{ij}\phi_{ij}t_{ij}B^{(\ell)}_{ij}+\Delta X^{(\ell),k}_i, + +where :math:`d^{(\bullet)}` are the divisors of the first block and +:math:`\Delta X` the transported keys. This is the reduction of +:meth:`~deepmd.dpmodel.descriptor.dpa4c.DescrptDPA4C.reduce_moments` over the +rescaled amplitudes :math:`\phi m`, written so that the correction reads +:math:`t` directly rather than the difference :math:`m-1`. The native spin +moments are those of the first block. +""" + +from __future__ import ( + annotations, +) + +from dataclasses import ( + dataclass, +) +from typing import ( + TYPE_CHECKING, + Any, +) + +import torch + +if TYPE_CHECKING: + from collections.abc import ( + Callable, + ) + + from .profile import ( + DescriptorProfile, + ) + +__all__ = [ + "HEADS", + "STATE_WIDTH", + "BlockLayout", + "block_layout", + "build_block_artifacts", + "further_block_moments", +] + +#: Heads of the attention, a width the compiled operator specializes on. +HEADS = 2 +#: Hidden width of the state encoder, a width the compiled operator +#: specializes on. +STATE_WIDTH = 16 +#: Floats of the record header: the cutoff of the block, the knees of the +#: three saturations, the logit cap and the null floor, and two padding words. +HEADER_WIDTH = 8 + + +def _aligned(size: int) -> int: + """Round a section width up to a whole number of 16-byte vectors.""" + return (size + 3) // 4 * 4 + + +@dataclass(frozen=True) +class BlockLayout: + r"""Float offsets of the sections of the record of one further block. + + Every section starts on a 16-byte boundary. Matrices are stored input-major, + as ``NativeLayer.w``: entry ``(k, c)`` of a map with ``n_out`` outputs is + at ``offset + k * n_out + c``. + + The two square maps of the edge network each follow the term of the fields + that enters the same pre-activation, so that the operator contracts one + stacked operand per map: the hidden layer reads ``[F, sat(phi)]`` through + ``[W_F; W_phi]``, and the logit reads ``[F, silu(hid)]`` through + ``[G; W_O]``, where ``G`` scatters the field gain of head ``h`` onto the + channels of that head. Both square maps are also stored transposed, for + the backward. + + Attributes + ---------- + channels + Scalar width :math:`C_0`. + degree_channels + Channel width of every degree from zero through ``lmax``. + descriptor_width + Width of the calibrated invariants that the node maps read. + keys + Offset of the key projection of every degree from one, ``(C_l, H)``. + node_weight + Offset of the input layer of the node maps, ``(descriptor_width, + node_width)``: the gate and the value of the state encoder, then the + hidden-layer term, then the null-mass logits, then padding. + node_width + Padded column count of the node input layer. + node_bias + Offset of the bias of the node input layer, ``(node_width,)``; only + the null-mass columns are nonzero. + state_output + Offset of the output layer of the state encoder, ``(STATE_WIDTH, C_0)``. + edge_field + Offset of the field term of the edge hidden layer, ``(L H, C_0)``, + immediately followed by its amplitude term ``(C_0, C_0)``. + edge_amplitude + Offset of the amplitude term of the edge hidden layer. + edge_gain + Offset of the field gain scattered onto the channels of every head, + ``(L H, C_0)``, immediately followed by the edge output layer. + edge_output + Offset of the edge output layer, ``(C_0, C_0)``. + edge_amplitude_t, edge_output_t + Offsets of the transposes of the two square maps. + edge_transport + Offset of the radial weight of the transport, ``(C_0, H)``. + outputs + Offset of the transport output of every degree from one, ``(H, C_l)``. + width + Floats of the whole record. + """ + + channels: int + degree_channels: tuple[int, ...] + descriptor_width: int + keys: tuple[int, ...] + node_weight: int + node_width: int + node_bias: int + state_output: int + edge_field: int + edge_amplitude: int + edge_gain: int + edge_output: int + edge_amplitude_t: int + edge_output_t: int + edge_transport: int + outputs: tuple[int, ...] + width: int + + @property + def lmax(self) -> int: + """Return the maximum angular degree.""" + return len(self.degree_channels) - 1 + + @property + def harmonic_width(self) -> int: + """Return the number of non-scalar harmonic components.""" + return (self.lmax + 1) ** 2 - 1 + + @property + def field_width(self) -> int: + """Return the number of fields of an edge, one per degree and head.""" + return self.lmax * HEADS + + @property + def source_width(self) -> int: + """Return the width of the source features of a node. + + The keys, harmonic-major with the heads innermost, then the encoded + state and the neighbor term of the edge hidden layer. + """ + return self.harmonic_width * HEADS + 2 * self.channels + + +def block_layout(profile: DescriptorProfile) -> BlockLayout: + """Derive the record layout of a further block from the compiled profile. + + The layout mirrors ``BlockLayout`` of the operator, which validates the + record width against it. + + Parameters + ---------- + profile + Compiled profile of the descriptor. + + Returns + ------- + BlockLayout + Offsets of every section of the record. + """ + channels = profile.channels + lmax = profile.lmax + fields = lmax * HEADS + offset = HEADER_WIDTH + keys = [] + for width in profile.degree_channels[1:]: + keys.append(offset) + offset += _aligned(width * HEADS) + node_width = _aligned(2 * STATE_WIDTH + channels + HEADS) + node_weight = offset + offset += profile.output_width * node_width + node_bias = offset + offset += node_width + state_output = offset + offset += STATE_WIDTH * channels + edge_field = offset + edge_amplitude = edge_field + fields * channels + offset = edge_amplitude + channels * channels + edge_gain = offset + edge_output = edge_gain + fields * channels + offset = edge_output + channels * channels + edge_amplitude_t = offset + offset += channels * channels + edge_output_t = offset + offset += channels * channels + edge_transport = offset + offset += channels * HEADS + outputs = [] + for width in profile.degree_channels[1:]: + outputs.append(offset) + offset += _aligned(HEADS * width) + return BlockLayout( + channels=channels, + degree_channels=tuple(profile.degree_channels), + descriptor_width=profile.output_width, + keys=tuple(keys), + node_weight=node_weight, + node_width=node_width, + node_bias=node_bias, + state_output=state_output, + edge_field=edge_field, + edge_amplitude=edge_amplitude, + edge_gain=edge_gain, + edge_output=edge_output, + edge_amplitude_t=edge_amplitude_t, + edge_output_t=edge_output_t, + edge_transport=edge_transport, + outputs=tuple(outputs), + width=offset, + ) + + +def _check_attention(attention: Any, layout: BlockLayout) -> None: + """Reject a block whose widths or constants the operator does not compile.""" + if attention.HEADS != HEADS or attention.STATE_WIDTH != STATE_WIDTH: + raise ValueError( + "The compressed DPA4C operator is compiled for " + f"{HEADS} attention heads and a state width of {STATE_WIDTH}, got " + f"{attention.HEADS} and {attention.STATE_WIDTH}." + ) + if tuple(attention.degree_channels) != layout.degree_channels: + raise ValueError( + "A further DPA4C block reads the degree channels " + f"{tuple(attention.degree_channels)}, but the descriptor profile " + f"has {layout.degree_channels}." + ) + if int(attention.descriptor_dim) != layout.descriptor_width: + raise ValueError( + "A further DPA4C block reads invariants of width " + f"{attention.descriptor_dim}, but the descriptor emits " + f"{layout.descriptor_width}." + ) + + +def _pack_block( + attention: Any, + cutoff: float, + layout: BlockLayout, + device: torch.device, +) -> torch.Tensor: + """Pack the weights of one further block into its record.""" + record = torch.zeros(layout.width, dtype=torch.float32, device=device) + + def put(offset: int, value: Any) -> None: + flat = torch.as_tensor(value).to(device=device, dtype=torch.float32) + flat = flat.reshape(-1) + record[offset : offset + flat.numel()] = flat + + header = ( + cutoff, + attention.STATE_KNEE, + attention.KEY_KNEE, + attention.AMPLITUDE_KNEE, + attention.LOGIT_CAP, + attention.NULL_FLOOR, + ) + put(0, torch.tensor(header, dtype=torch.float64, device=device)) + for offset, projection in zip(layout.keys, attention.key_projections, strict=True): + put(offset, projection.w) + + # The three maps of the calibrated invariants share their input, so they + # form one layer: gate and value of the state encoder, the hidden-layer + # term of the neighbor, then the null-mass logits of the center. + channels = layout.channels + node = torch.zeros( + layout.descriptor_width, + layout.node_width, + dtype=torch.float32, + device=device, + ) + node[:, : 2 * STATE_WIDTH] = torch.as_tensor(attention.state_encoder.layers[0].w) + node[:, 2 * STATE_WIDTH : 2 * STATE_WIDTH + channels] = torch.as_tensor( + attention.hidden_state.w + ) + null_begin = 2 * STATE_WIDTH + channels + node[:, null_begin : null_begin + HEADS] = torch.as_tensor(attention.null_mass.w) + put(layout.node_weight, node) + bias = torch.zeros(layout.node_width, dtype=torch.float32, device=device) + bias[null_begin : null_begin + HEADS] = torch.as_tensor(attention.null_mass.b) + put(layout.node_bias, bias) + put(layout.state_output, attention.state_encoder.layers[-1].w) + + put(layout.edge_field, attention.hidden_field.w) + amplitude = torch.as_tensor(attention.hidden_amplitude.w) + output = torch.as_tensor(attention.hidden_output.w) + put(layout.edge_amplitude, amplitude) + put(layout.edge_amplitude_t, amplitude.T) + # Amplitude channel c follows head c mod H, so the gain of field (l, h) + # reaches exactly the channels of head h. + gain = torch.as_tensor(attention.adam_field_gain).to( + device=device, dtype=torch.float32 + ) + head = torch.arange(channels, dtype=torch.int64, device=device) % HEADS + field_head = ( + torch.arange(layout.field_width, dtype=torch.int64, device=device) % HEADS + ) + scatter = gain.reshape(layout.field_width)[:, None] * ( + head[None, :] == field_head[:, None] + ).to(torch.float32) + put(layout.edge_gain, scatter) + put(layout.edge_output, output) + put(layout.edge_output_t, output.T) + put(layout.edge_transport, attention.transport_radial.w) + for offset, projection in zip( + layout.outputs, attention.transport_outputs, strict=True + ): + put(offset, projection.w) + return record + + +def build_block_artifacts( + descriptor: Any, + profile: DescriptorProfile, +) -> torch.Tensor: + """Pack every further block of a descriptor into the operator records. + + Parameters + ---------- + descriptor + Evaluated pt_expt DPA4C descriptor. + profile + Compiled profile of the descriptor. + + Returns + ------- + torch.Tensor + Records with shape ``(n_blocks - 1, layout.width)``, fp32, on the + device of the descriptor; shape ``(0, 0)`` for a single block. + + Raises + ------ + ValueError + If a block carries widths or constants the operator does not compile. + """ + device = descriptor.stddev.device + if not descriptor.attentions: + return torch.zeros(0, 0, dtype=torch.float32, device=device) + layout = block_layout(profile) + records = [] + with torch.no_grad(): + for attention, cutoff in zip( + descriptor.attentions, descriptor.block_rcut[1:], strict=True + ): + _check_attention(attention, layout) + records.append(_pack_block(attention, float(cutoff), layout, device)) + return torch.stack(records).contiguous() + + +# === Portable equations === + + +def _soft_saturate(value: torch.Tensor, knee: float) -> torch.Tensor: + scale = value.abs().clamp_min(knee) + scaled_value = value / scale + scaled_knee = knee / scale + return ( + knee + * scaled_value + / torch.sqrt(scaled_value * scaled_value + scaled_knee * scaled_knee) + ) + + +def _c3_envelope(radius: torch.Tensor, rcut: float) -> torch.Tensor: + u = torch.clamp((rcut - radius) / rcut, min=0.0, max=1.0) + x = 1.0 - u + series = 1.0 + x * (4.0 + x * (10.0 + x * (20.0 + 35.0 * x))) + return u**4 * series + + +def _section( + record: torch.Tensor, offset: int, rows: int, columns: int +) -> torch.Tensor: + return record[offset : offset + rows * columns].reshape(rows, columns) + + +def further_block_moments( + record: torch.Tensor, + layout: BlockLayout, + first_moments: list[torch.Tensor], + previous_moments: list[torch.Tensor], + invariants: torch.Tensor, + amplitude: torch.Tensor, + basis: torch.Tensor, + envelope: torch.Tensor, + radius: torch.Tensor, + source: torch.Tensor, + destination: torch.Tensor, + scalar_divisor: torch.Tensor, + angular_divisor: torch.Tensor, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, +) -> list[torch.Tensor]: + """Evaluate one further block on the compressed record. + + The equations are those of + :class:`~deepmd.dpmodel.descriptor.dpa4c_nn.BlockAttention` followed by the + reduction of the block, with the correction of the moments formed as in + the module docstring. + + Parameters + ---------- + record + Packed record of the block with shape ``(layout.width,)``. + layout + Layout of the record. + first_moments + Normalized geometric moments of the first block, one tensor per + degree with shape ``(N, 2 l + 1, C_l)``, which the block corrects. + previous_moments + Geometric moments of the previous block, shaped as ``first_moments``, + from which the keys are formed. + invariants + Calibrated invariants of the previous block with shape ``(N, D)``. + amplitude + Enveloped first-block amplitudes with shape ``(E, C_0)``. + basis + Masked Cartesian harmonics with shape ``(E, (L + 1) ** 2)``. + envelope + Masked first-block envelope with shape ``(E,)``. + radius + Regularized edge lengths with shape ``(E,)`` in Å. + source, destination + Source and destination node of every edge with shape ``(E,)``. + scalar_divisor, angular_divisor + Divisors of the first block with shape ``(N, 1)``. + exchange + Refresh of the halo rows of a node feature from their owners, or + ``None`` for a graph without halo nodes. + + Returns + ------- + list[torch.Tensor] + Moments of the block, one tensor per degree, shaped as + ``first_moments``. + """ + cutoff, state_knee, key_knee, amplitude_knee, logit_cap, null_floor = ( + float(value) for value in record[:6].tolist() + ) + channels = layout.channels + lmax = layout.lmax + node_count = invariants.shape[0] + edge_count = amplitude.shape[0] + dtype = amplitude.dtype + + # === Step 1. Node maps: saturated keys, state, hidden term, null mass === + keys = [] + for degree, width in enumerate(layout.degree_channels[1:], start=1): + projection = _section(record, layout.keys[degree - 1], width, HEADS) + block = previous_moments[degree] @ projection.to(dtype) + squared = (block * block).sum(dim=1, keepdim=True) + keys.append(block / torch.sqrt(1.0 + squared / (key_knee * key_knee))) + keys = torch.cat(keys, dim=1) + saturated_invariants = _soft_saturate(invariants, state_knee) + pre = saturated_invariants @ _section( + record, layout.node_weight, layout.descriptor_width, layout.node_width + ).to(dtype) + record[layout.node_bias : layout.node_bias + layout.node_width].to( + dtype + ) + gate = pre[:, :STATE_WIDTH] + value = pre[:, STATE_WIDTH : 2 * STATE_WIDTH] + state = (torch.nn.functional.silu(gate) * value) @ _section( + record, layout.state_output, STATE_WIDTH, channels + ).to(dtype) + hidden_node = pre[:, 2 * STATE_WIDTH : 2 * STATE_WIDTH + channels] + null_logit = pre[:, 2 * STATE_WIDTH + channels : 2 * STATE_WIDTH + channels + HEADS] + key_end = layout.harmonic_width * HEADS + sources = torch.cat( + [keys.reshape(node_count, key_end), state, hidden_node], + dim=1, + ) + if exchange is not None: + sources = exchange(sources) + + # === Step 2. Fields of the neighbor along the reversed bond === + source_keys = sources[source, :key_end].reshape( + edge_count, layout.harmonic_width, HEADS + ) + source_state = sources[source, key_end : key_end + channels] + source_hidden = sources[source, key_end + channels :] + sign = torch.cat( + [ + torch.full( + (2 * degree + 1,), (-1.0) ** degree, dtype=dtype, device=basis.device + ) + for degree in range(1, lmax + 1) + ] + ) + signed = (basis[:, 1:] * sign)[:, :, None] * source_keys + fields = torch.stack( + [ + signed[:, degree * degree - 1 : (degree + 1) * (degree + 1) - 1, :].sum( + dim=1 + ) + for degree in range(1, lmax + 1) + ], + dim=1, + ) + + # === Step 3. Logit of every amplitude channel and its correction === + saturated = _soft_saturate(amplitude, amplitude_knee) + hidden = ( + source_hidden + + fields.reshape(edge_count, layout.field_width) + @ _section(record, layout.edge_field, layout.field_width, channels).to(dtype) + + saturated + @ _section(record, layout.edge_amplitude, channels, channels).to(dtype) + ) + flat_fields = fields.reshape(edge_count, layout.field_width) + logit = ( + source_state + + flat_fields + @ _section(record, layout.edge_gain, layout.field_width, channels).to(dtype) + + torch.nn.functional.silu(hidden) + @ _section(record, layout.edge_output, channels, channels).to(dtype) + ) + block_envelope = _c3_envelope(radius, cutoff) + delta = amplitude * (block_envelope[:, None] * torch.tanh(logit)) + + # === Step 4. Softmax transport of the neighbor keys === + weight = envelope * block_envelope + capped = logit_cap * torch.tanh(logit[:, :HEADS] / logit_cap) + mass = (weight * weight)[:, None] * torch.exp(capped) + denominator = ( + torch.zeros(node_count, HEADS, dtype=dtype, device=basis.device).index_add_( + 0, destination, mass + ) + + torch.nn.functional.softplus(null_logit) + + null_floor + ) + radial_weight = saturated @ _section( + record, layout.edge_transport, channels, HEADS + ).to(dtype) + transported = torch.zeros( + node_count, layout.harmonic_width, HEADS, dtype=dtype, device=basis.device + ).index_add_(0, destination, (mass * radial_weight)[:, None, :] * source_keys) + transported = transported / denominator[:, None, :] + + # === Step 5. Correct the moments of the first block === + corrected = [ + first_moments[0] + + torch.zeros( + node_count, 1, channels, dtype=dtype, device=basis.device + ).index_add_(0, destination, delta[:, None, :]) + / scalar_divisor[:, :, None] + ] + for degree, width in enumerate(layout.degree_channels[1:], start=1): + harmonics = basis[:, degree * degree : (degree + 1) * (degree + 1)] + payload = harmonics[:, :, None] * ( + delta[:, None, :width] * envelope[:, None, None] + ) + reduced = torch.zeros( + node_count, 2 * degree + 1, width, dtype=dtype, device=basis.device + ).index_add_(0, destination, payload) + output = _section(record, layout.outputs[degree - 1], HEADS, width).to(dtype) + start = degree * degree - 1 + corrected.append( + first_moments[degree] + + reduced / angular_divisor[:, :, None] + + transported[:, start : start + 2 * degree + 1, :] @ output + ) + return corrected diff --git a/deepmd/pt_expt/kernels/dpa4c/canonical.py b/deepmd/pt_expt/kernels/dpa4c/canonical.py index 4c3f8eedd8..692a5b5fa5 100644 --- a/deepmd/pt_expt/kernels/dpa4c/canonical.py +++ b/deepmd/pt_expt/kernels/dpa4c/canonical.py @@ -18,30 +18,50 @@ ) if TYPE_CHECKING: + from collections.abc import ( + Callable, + ) + from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, CanonicalGraph, ) _cpu_library: torch.library.Library | None = None -def canonical_model_eligible(model: Any) -> bool: - """Return whether a model can use the compact source-only graph ABI. +def _canonical_ineligibility(model: Any, *, as_compressed: bool = False) -> str | None: + """Return the condition under which the compact canonical ABI fails a model. The compact ABI exists so that a device-resident neighbor list can reach the descriptor without a host round trip, which is a property of the CUDA / Kokkos deployment. Only that backend implements its operators, so a CPU target keeps the generic graph lower, whose operators it does implement and whose extra cost is one index tensor. + + Parameters + ---------- + model + Model to deploy. + as_compressed + Judge the model in the state that its compression leaves: the + descriptor compressed and the charge state of a long-range module + that reads one folded (see ``DPAtomicModel.enable_compression``). + + Returns + ------- + str or None + The first condition that fails, as a clause, or ``None`` when the + compact canonical operators serve the model. """ if backend_device_type() != "cuda": - return False + return "the compact canonical operators run on CUDA devices" atomic_model = getattr(model, "atomic_model", None) # A bridged composition deploys like its learned part: the fused operator # evaluates the analytical pair potential in the same edge scan. parts = None if atomic_model is None else atomic_model.fused_decomposition() if parts is None: - return False + return "the model is not one DPA4C energy model" descriptor = parts[0].descriptor fitting = parts[0].fitting_net from deepmd.pt_expt.descriptor.dpa4c import ( @@ -49,30 +69,64 @@ def canonical_model_eligible(model: Any) -> bool: ) if not isinstance(descriptor, DescrptDPA4C): - return False - if not bool(getattr(descriptor, "compress", False)): - return False + return "the descriptor is not DPA4C" + if not (as_compressed or bool(getattr(descriptor, "compress", False))): + return "the descriptor is not compressed" if getattr(descriptor, "exclude_types", None): - return False + return "the descriptor excludes type pairs" if getattr(atomic_model, "pair_excl", None) is not None: - return False + return "the model excludes type pairs (pair_exclude_types)" if getattr(atomic_model, "atom_excl", None) is not None: - return False + return "the model excludes atom types (atom_exclude_types)" # A latent-charge long-range module joins the pipeline through the node # positions and the cells, which its operator reads in place of a pair - # list or a mesh; that pipeline evaluates no pair potential. + # list or a mesh; that pipeline reads no frame input and evaluates no pair + # potential, and further message-passing blocks on the fused long-range + # operator alone. if parts[0].has_long_range(): + from deepmd.pt_expt.kernels.dpa4c.canonical_long_range import ( + fused_long_range_eligible, + ) + from deepmd.pt_expt.kernels.long_range import ( + MAX_CHANNELS, + MAX_GAUSSIANS, + MAX_ORDER, + ) + from deepmd.pt_expt.kernels.long_range import ( + op_available as latent_charge_op_available, + ) from deepmd.pt_expt.long_range.latent_charge import ( LatentChargeLongRange, ) long_range = parts[0].long_range - if not ( - isinstance(long_range, LatentChargeLongRange) - and long_range.operator_eligible() - and parts[1] is None - ): - return False + if not isinstance(long_range, LatentChargeLongRange): + return "the long-range module is not a latent-charge module" + if not latent_charge_op_available(): + return "the loaded library lacks the latent-charge operator" + if not long_range.operator_eligible(): + return ( + "the long-range module is not one the long-range operator " + f"evaluates (the les kernel or the sog kernel of up to " + f"{MAX_GAUSSIANS} Gaussians, up to {MAX_CHANNELS} charge " + f"channels, B-splines of order up to {MAX_ORDER}, and a charge " + "network without frame or atomic parameters)" + ) + if long_range.uses_charge_spin() and not as_compressed: + return ( + "the long-range module reads the charge state of each frame, " + "which the compression of the whole model folds" + ) + if parts[1] is not None: + return "the model combines a long-range module with a pair potential" + if descriptor.attentions and not fused_long_range_eligible(long_range): + return ( + "the charge network is not one the fused long-range operator, " + "which evaluates further message-passing blocks, reproduces " + "(one channel in float32 with tanh or silu hidden layers whose " + "widths are multiples of four, without resnet_dt), or the " + "loaded library lacks that operator" + ) from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( mega_eligible, ) @@ -80,7 +134,76 @@ def canonical_model_eligible(model: Any) -> bool: fitting_eligible, ) - return mega_eligible(descriptor) and fitting_eligible(fitting) + if not mega_eligible(descriptor): + return "the fused kernels are not compiled for the descriptor profile" + if not fitting_eligible(fitting): + return ( + "the energy fitting is not one the fused fitting kernels reproduce " + "(float32 with tanh or silu hidden layers whose widths are " + "multiples of four, without resnet_dt, frame or atomic parameters " + "or a case embedding)" + ) + return None + + +def canonical_model_unsupported_reason( + model: Any, *, as_compressed: bool = False +) -> str | None: + """Return why a compressed DPA4C model of several blocks cannot be deployed. + + On the CUDA backend, the further message-passing blocks of a compressed + DPA4C descriptor are evaluated by the compact canonical operators alone; + the operators of a generic lower evaluate one block. Such a model must + not fall back to a generic lower, which would silently evaluate the + uncompressed equations, so the deployment reports the condition under + which the compact canonical operators fail it instead. + + Parameters + ---------- + model + Model to deploy. + as_compressed + Judge the model in the state that its compression leaves, as a freeze + does before it compresses the model (see + :func:`~deepmd.pt_expt.utils.serialization.compressed_export_unsupported_reason`). + + Returns + ------- + str or None + Diagnostic of the failing condition, or ``None`` when the compact + canonical path serves the model or the model does not need it. + """ + if backend_device_type() != "cuda": + return None + atomic_model = getattr(model, "atomic_model", None) + parts = None if atomic_model is None else atomic_model.fused_decomposition() + if parts is None: + return None + descriptor = parts[0].descriptor + if not ( + (as_compressed or bool(getattr(descriptor, "compress", False))) + and getattr(descriptor, "attentions", None) + ): + return None + condition = _canonical_ineligibility(model, as_compressed=as_compressed) + if condition is None and not op_available(): + condition = "the loaded library lacks the compact canonical operators" + if condition is None: + return None + return ( + "A compressed DPA4C model with further message-passing blocks " + "(`n_blocks` > 1) deploys on a GPU through the compact canonical " + f"operators alone, which do not serve this model: {condition}. " + "Deploy the uncompressed archive." + ) + + +def canonical_model_eligible(model: Any) -> bool: + """Return whether a model can use the compact source-only graph ABI. + + See :func:`_canonical_ineligibility` for the conditions. + """ + return _canonical_ineligibility(model) is None def op_available() -> bool: @@ -294,10 +417,11 @@ def _cpu_energy_force( The force and the virial are assembled by index reduction in fp64. The per-atom virial is attributed to the source nodes that the source CSR - lists, and is zero when two-entry placeholders take the place of the CSR. - A frame whose energy or virial is not finite reports every force of its - nodes, and every magnetic force, as not a number, as the CUDA operator - does. + lists, and is zero when two-entry placeholders take the place of the CSR; + the part of the switch totals of a source gate belongs to the node of the + row that holds each edge, its destination. A frame whose energy or virial + is not finite reports every force of its nodes, and every magnetic force, + as not a number, as the CUDA operator does. """ from deepmd.dpmodel.utils.neighbor_graph import ( frame_id_from_n_node, @@ -348,19 +472,37 @@ def _cpu_energy_force( *args[:_DESCRIPTOR_TAIL_COUNT], ) # The trailing fitting-route table, which a caller may leave to its default, - # sets only the speed of the CUDA operator. + # sets only the speed of the CUDA operator, and so do the trailing cutoffs + # of the further blocks: the reference reads them from the records and + # evaluates every block on the whole graph. ws, bs, resnets, w_head, b_head, bias_atom_e, act, _tile, pair_table = args[ _DESCRIPTOR_TAIL_COUNT : _DESCRIPTOR_TAIL_COUNT + 9 ] - descriptor, state = _cpu_forward(*descriptor_args) + _routes, blocks, halo_send, halo_swaps, communicator = ( + *args[_DESCRIPTOR_TAIL_COUNT + 9 :], + *(None,) * 5, + )[:5] + further = { + "blocks_record": blocks, + "exchange": _self_swap_exchange( + halo_send, halo_swaps, communicator, node_count + ), + } + descriptor, state = _cpu_forward(*descriptor_args, **further) energy, saved = torch.ops.deepmd.graph_fitting( descriptor, atype, ws, bs, resnets, w_head, b_head, bias_atom_e, act ) gradient = torch.ops.deepmd.graph_fitting_backward( seed.reshape(-1, 1), saved, ws, bs, resnets, w_head, act ) - edge_gradient, spin_gradient, edge_spin_gradient, pair_energy = _generic_backward( - gradient, state, *descriptor_args, pair=(pair_table, seed) + ( + edge_gradient, + row_gradient, + spin_gradient, + edge_spin_gradient, + pair_energy, + ) = _generic_backward( + gradient, state, *descriptor_args, pair=(pair_table, seed), **further ) if pair_table.numel(): energy = energy + pair_energy @@ -368,8 +510,12 @@ def _cpu_energy_force( edge_index, edge_mask, _ = _generic_topology(source, destination_row_ptr) keep = edge_mask[:, None].to(torch.float64) - g = edge_gradient.to(torch.float64) * keep - outer = -(g[:, :, None] * edge_vec.to(torch.float64)[:, None, :]) + source_part = edge_gradient.to(torch.float64) * keep + row_part = row_gradient.to(torch.float64) * keep + g = source_part + row_part + vector = edge_vec.to(torch.float64)[:, None, :] + source_outer = -(source_part[:, :, None] * vector) + row_outer = -(row_part[:, :, None] * vector) source_index, destination_index = edge_index[0], edge_index[1] destination_force = torch.zeros( node_count, 3, dtype=torch.float64, device=device @@ -387,7 +533,7 @@ def _cpu_energy_force( atom_energy[out_of_range] = torch.nan node_virial = torch.zeros( node_count, 3, 3, dtype=torch.float64, device=device - ).index_add_(0, destination_index, outer) + ).index_add_(0, destination_index, source_outer + row_outer) # Padding nodes past the last frame belong to none: they enter no frame # total, as in the CUDA operator. frame_id = frame_id_from_n_node(n_node, n_total=node_count) @@ -405,7 +551,8 @@ def _cpu_energy_force( torch.arange(node_count, dtype=torch.int64, device=device), listed ) positions = source_order[: int(source_row_ptr[-1])].to(torch.int64) - atom_virial.index_add_(0, rows, outer[positions]) + atom_virial.index_add_(0, rows, source_outer[positions]) + atom_virial.index_add_(0, destination_index, row_outer) if spin_gradient.ndim == 2: spin_force = torch.zeros( node_count, 3, dtype=torch.float64, device=device @@ -486,7 +633,72 @@ def _generic_topology( _DESCRIPTOR_TAIL_COUNT = _DESCRIPTOR_ARGUMENT_COUNT - 4 -def _cpu_forward(*args: Any) -> tuple[torch.Tensor, torch.Tensor]: +def _self_swap_exchange( + send_nodes: torch.Tensor | None, + swaps: torch.Tensor | None, + communicator: torch.Tensor | None, + node_count: int, +) -> Callable[[torch.Tensor], torch.Tensor] | None: + """Return the halo exchange of a border plan for the reference evaluation. + + The reference runs in one process, so it serves the plans of a single + domain, whose swaps all copy rows of this process: swap by swap, the halo + rows from the first receive take the rows of the send list, so that a + swap may send the rows an earlier swap received. ``None`` without a plan, + or for a plan without swaps. + + Raises + ------ + RuntimeError + If the plan names another rank or does not fill the halo rows. + """ + if swaps is None or swaps.shape[0] == 0: + return None + if int(communicator.reshape(-1)[0]) != 0: + raise RuntimeError( + "dpa4c_canonical_compress_energy_force: the reference evaluation " + "serves the border plan of a single process, but a communicator " + "was given" + ) + table = swaps.to(device="cpu", dtype=torch.int64).tolist() + send = send_nodes.to(torch.int64) + copies = [] + offset = 0 + expected = table[0][4] + for send_rank, receive_rank, sent, received, first in table: + if send_rank != receive_rank or sent != received or first != expected: + raise RuntimeError( + "dpa4c_canonical_compress_energy_force: the reference " + "evaluation copies the halo rows of self swaps that fill the " + f"halo in order, got the swap {(send_rank, receive_rank, sent, received, first)}" + ) + receive = torch.arange( + first, first + received, dtype=torch.int64, device=send.device + ) + copies.append((receive, send[offset : offset + sent])) + offset += sent + expected = first + received + if expected != node_count: + raise RuntimeError( + "dpa4c_canonical_compress_energy_force: the swaps of the border " + f"plan fill the rows up to {expected} of {node_count}" + ) + + def exchange(rows: torch.Tensor) -> torch.Tensor: + for receive, sent in copies: + rows = rows.index_copy( + 0, receive.to(rows.device), rows[sent.to(rows.device)] + ) + return rows + + return exchange + + +def _cpu_forward( + *args: Any, + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, +) -> tuple[torch.Tensor, torch.Tensor]: from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( _reference_forward as generic_forward, ) @@ -506,20 +718,28 @@ def _cpu_forward(*args: Any) -> tuple[torch.Tensor, torch.Tensor]: *tail[:-_CANONICAL_SCALAR_COUNT], True, *tail[-_CANONICAL_SCALAR_COUNT:], + blocks_record=blocks_record, + exchange=exchange, ) def _generic_backward( *args: Any, pair: tuple[torch.Tensor, torch.Tensor] | None = None, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - """Run the generic reference backward on a compact payload. + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Run the generic reference cotangents on a compact payload. ``pair`` is the series table and the energy cotangent of an analytical pair potential; the compact descriptor operators carry none. + ``blocks_record`` and ``exchange`` are those of the reference descriptor. + The results are those of ``_reference_cotangents``, whose second one is + the part of the coordinate cotangent that belongs to the destination of + every edge. """ from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( - _reference_backward as generic_backward, + _reference_cotangents as generic_cotangents, ) descriptor_gradient, state, edge_vec, source, destination_row_ptr, atype, *tail = ( @@ -530,7 +750,7 @@ def _generic_backward( destination_row_ptr, ) no_pair = edge_vec.new_empty(0) - return generic_backward( + return generic_cotangents( descriptor_gradient, state, edge_vec, @@ -543,11 +763,16 @@ def _generic_backward( True, *tail[-_CANONICAL_SCALAR_COUNT:], *((no_pair, no_pair) if pair is None else pair), + blocks_record=blocks_record, + exchange=exchange, ) def _cpu_backward(*args: Any) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - return _generic_backward(*args)[:3] + edge_gradient, row_gradient, spin_gradient, edge_spin_gradient, _ = ( + _generic_backward(*args) + ) + return edge_gradient + row_gradient, spin_gradient, edge_spin_gradient def _cpu_backward_inplace( @@ -605,6 +830,7 @@ def dpa4c_canonical_compress_energy_force( spin: torch.Tensor | None = None, pair_table: torch.Tensor | None = None, fitting_routes: list[int] | None = None, + border: BorderPlan | None = None, ) -> tuple[ torch.Tensor, torch.Tensor, @@ -635,6 +861,16 @@ def dpa4c_canonical_compress_energy_force( configuration short of three atoms within about 0.01 Å of one atom reaches, is not detected. + A descriptor of several message-passing blocks evaluates every further + block from the records of its compression. On the node set of one domain + of a decomposed frame, whose halo nodes follow its owned nodes, the + operator then refreshes the features of the halo nodes that the further + blocks read through ``border`` and evaluates the owned nodes alone: their + energies, the per-node virials of the edges they own, and the force of + every edge they own on both of its nodes, so that the forces on the halo + nodes are the contributions of this domain, which the caller folds onto + their owners. + Parameters ---------- descriptor @@ -663,6 +899,11 @@ def dpa4c_canonical_compress_energy_force( Fitting-route table of the CUDA operator, which sets only its speed (``deepmd.pt_expt.kernels.fitting_routes``). ``None`` or an empty table leaves the routes to the rules of the operator. + border + Border plan of the node set for a descriptor of several blocks, whose + owned nodes are the leading ``n_local`` nodes of its single frame, or + ``None`` for a node set without halo nodes. A descriptor of one block + takes none. Returns ------- @@ -709,6 +950,11 @@ def dpa4c_canonical_compress_energy_force( ensure_fitting_registered() if not mega_eligible(descriptor): raise ValueError("model is not eligible for compact canonical DPA4C inference") + if border is not None and not descriptor.attentions: + raise ValueError( + "a border plan serves the further message-passing blocks, but the " + "descriptor has one block" + ) network = fitting_operator_arguments(fitting) return torch.ops.deepmd.dpa4c_canonical_compress_energy_force( @@ -736,4 +982,13 @@ def dpa4c_canonical_compress_energy_force( # AOTInductor proxy executor of torch 2.13 and earlier hands a # serialized empty int list to the operator as None. list(fitting_routes) if fitting_routes else None, + descriptor.compress_blocks if descriptor.attentions else None, + *( + (None, None, None) + if border is None + else (border.send_nodes, border.swaps, border.communicator) + ), + [float(cutoff) for cutoff in descriptor.block_rcut[1:]] + if descriptor.attentions + else None, ) diff --git a/deepmd/pt_expt/kernels/dpa4c/canonical_long_range.py b/deepmd/pt_expt/kernels/dpa4c/canonical_long_range.py index b588eb04ef..78d9ca4be7 100644 --- a/deepmd/pt_expt/kernels/dpa4c/canonical_long_range.py +++ b/deepmd/pt_expt/kernels/dpa4c/canonical_long_range.py @@ -14,6 +14,7 @@ if TYPE_CHECKING: from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, CanonicalGraph, ) @@ -25,7 +26,9 @@ def fused_long_range_eligible(long_range: Any) -> bool: fitting kernels reproduce, beside the compressed descriptor and the energy fitting that the compact canonical lower already requires; a module whose charge network they do not reproduce, or a library without the operator, - takes :func:`dpa4c_canonical_long_range_energy_force`. + takes :func:`dpa4c_canonical_long_range_energy_force`, which evaluates a + descriptor of one block, so that a descriptor of further message-passing + blocks with such a module is not deployed in compressed form on a GPU. """ from deepmd.pt_expt.kernels.dpa4c.canonical import ( long_range_op_available, @@ -49,6 +52,7 @@ def dpa4c_canonical_compress_long_range_energy_force( atom_bias: torch.Tensor, fitting_routes: list[int] | None = None, charge_fitting_routes: list[int] | None = None, + border: BorderPlan | None = None, ) -> tuple[ torch.Tensor, torch.Tensor, @@ -68,6 +72,12 @@ def dpa4c_canonical_compress_long_range_energy_force( It derives the ownership mask from the frame counts, and the charged nodes of the module are the owned real nodes. + A descriptor of several message-passing blocks evaluates every further + block as that operator does, and the charges read the descriptor of the + last block. A node set of one domain of a decomposed frame, whose halo + nodes follow its owned nodes, refreshes the features of its halo nodes + through ``border`` and evaluates its owned nodes alone, as there. + Parameters ---------- descriptor @@ -103,6 +113,10 @@ def dpa4c_canonical_compress_long_range_energy_force( Fitting-route table of the charge network. ``None`` or an empty table leaves the routes of its network to the rules of the operator, for either table. + border + Border plan of the node set for a descriptor of several blocks, whose + communicator is ``communicator``, or ``None`` for a node set without + halo nodes. Returns ------- @@ -142,6 +156,11 @@ def dpa4c_canonical_compress_long_range_energy_force( ensure_registered() ensure_fitting_registered() + if border is not None and not descriptor.attentions: + raise ValueError( + "a border plan serves the further message-passing blocks, but the " + "descriptor has one block" + ) network = fitting_operator_arguments(fitting) charge_net = long_range.charge_net charges = fitting_operator_arguments(charge_net) @@ -193,6 +212,11 @@ def dpa4c_canonical_compress_long_range_energy_force( # serialized empty int list to the operator as None. list(fitting_routes) if fitting_routes else None, list(charge_fitting_routes) if charge_fitting_routes else None, + descriptor.compress_blocks if descriptor.attentions else None, + *((None, None) if border is None else (border.send_nodes, border.swaps)), + [float(cutoff) for cutoff in descriptor.block_rcut[1:]] + if descriptor.attentions + else None, ) @@ -225,7 +249,8 @@ def dpa4c_canonical_long_range_energy_force( fitting Eligible pt_expt energy fitting network. long_range - Long-range module whose ``operator_eligible()`` holds. + Long-range module whose ``operator_eligible()`` holds and whose + charge state, if it reads one, is folded. graph Canonical graph whose ``source`` has shape ``(E,)`` in ``uint32`` or ``int64``, or shape ``(E, W)`` in ``uint8`` for the exported bytes of diff --git a/deepmd/pt_expt/kernels/dpa4c/graph_compress.py b/deepmd/pt_expt/kernels/dpa4c/graph_compress.py index 8e9532280b..f8c34644d5 100644 --- a/deepmd/pt_expt/kernels/dpa4c/graph_compress.py +++ b/deepmd/pt_expt/kernels/dpa4c/graph_compress.py @@ -88,8 +88,18 @@ UNIT_CONTACT_RADIUS, ) +from .attention import ( + block_layout, + build_block_artifacts, + further_block_moments, +) +from .profile import ( + DescriptorProfile, +) + if TYPE_CHECKING: from collections.abc import ( + Callable, Sequence, ) @@ -108,6 +118,7 @@ "ef_op_available", "ensure_registered", "fitting_energy_and_gradient", + "graph_operator_eligible", "mega_eligible", "op_available", "reduce_edge_spin_gradient", @@ -214,8 +225,9 @@ def mega_eligible(descriptor: Any) -> bool: Native spin is a compiled variant of the same kernels rather than a separate operator, and every spin width follows from the channel count, so a spin-conditioned descriptor is eligible on exactly the conditions a - spin-free one is. Each condition below is a width the compiled operator - specializes on. + spin-free one is. The further message-passing blocks read the widths of + the first one, so any depth is eligible. Each condition below is a width + the compiled operator specializes on. Eligibility is a property of the descriptor alone: it decides whether the compression artifacts are worth building, which a snapshot does once for @@ -240,6 +252,27 @@ def mega_eligible(descriptor: Any) -> bool: ) +def graph_operator_eligible(descriptor: Any) -> bool: + """Return whether the NeighborGraph operators evaluate the descriptor. + + The descriptor operator and the fused energy-force route of the generic + graph compile one reduction, so a descriptor with further blocks takes the + compact canonical operator on its deployment path and its own equations + elsewhere. + + Parameters + ---------- + descriptor + Descriptor instance, which need not be a DPA4C. + + Returns + ------- + bool + Whether the NeighborGraph operators cover this configuration. + """ + return mega_eligible(descriptor) and int(getattr(descriptor, "n_blocks", 1)) == 1 + + def compression_ineligibility_reason(descriptor: Any) -> str | None: """Return why a DPA4C descriptor cannot build a compressed snapshot. @@ -292,69 +325,6 @@ def compression_ineligibility_reason(descriptor: Any) -> str | None: # === Compiled profile === -@dataclass(frozen=True) -class DescriptorProfile: - r"""Describe every width the compiled operator derives from its inputs. - - Attributes - ---------- - channels - Scalar degree-zero width :math:`C_0`. - lmax - Maximum angular degree. - degree_channels - Channel width of each degree from zero through ``lmax``. - ranks - Bispectrum probe rank of each degree from one through ``lmax``. - moment_width - Flat moment width :math:`S=\\sum_\\ell(2\\ell+1)C_\\ell`. - output_width - Invariant descriptor width consumed by the fitting network. - gram_base - Descriptor coordinate of the first degree-one Gram entry. - bispectrum_base - Descriptor coordinate of the first bispectrum entry. - spin_width - Width of the trailing native-spin invariant block. - basis - Width of the low-rank expansion of the scalar-only channels, zero for - a profile that admits no expansion. - """ - - channels: int - lmax: int - degree_channels: tuple[int, ...] - ranks: tuple[int, ...] - moment_width: int - output_width: int - gram_base: int - bispectrum_base: int - spin_channels: int - spin_width: int - basis: int - - @property - def state_width(self) -> int: - """Return the saved-state width: the moments plus both normalizers.""" - return self.moment_width + 2 - - @property - def has_spin(self) -> bool: - """Return whether the compiled profile carries the spin families.""" - return self.spin_channels > 0 - - @property - def spin_slice(self) -> slice: - """Return the descriptor columns holding the spin invariants. - - The layout closes with the spin invariants, the two moment divisors - and the center type tail, so the block is addressed from the end and - is empty for a spin-free profile. - """ - stop = self.output_width - 2 - self.degree_channels[0] - return slice(stop - self.spin_width, stop) - - def descriptor_profile( channels: int, lmax: int, @@ -935,12 +905,13 @@ def build_compression_artifacts( Radial spline coefficients, the low-rank table of the scalar-only channels and its expansion (empty when no basis is adopted), metadata, ordered FiLM, mixing and type caches, padded readout projections, - sparse angular couplings, and the output calibration. + sparse angular couplings, the output calibration, and the records of + the further message-passing blocks (empty for a single block). Raises ------ ValueError - If the descriptor excludes type pairs, or is not an fp32 model with a + If the descriptor excludes type pairs or is not an fp32 model with a compiled specialization. """ reason = compression_ineligibility_reason(descriptor) @@ -1004,6 +975,7 @@ def build_compression_artifacts( ), "output_mean": output_mean.detach().contiguous(), "output_inv_std": output_inv_std.detach().contiguous(), + "blocks": build_block_artifacts(descriptor, profile), **build_charge_state_artifacts(descriptor, descriptor.default_chg_spin), } @@ -1349,8 +1321,8 @@ def _edge_envelope( rcut: float, f_inner: float, f_outer: float, -) -> tuple[torch.Tensor, torch.Tensor]: - """Evaluate the edge envelope and the length the radial table reads. +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Evaluate the edge envelope, the length the radial table reads and the switch. The window of a pair is two dimensionless fractions of that pair's own length scale ``contact``, so both are functions of the reduced distance @@ -1360,24 +1332,92 @@ def _edge_envelope( the window midpoint below the inner fraction and rises with the antiderivative ``S(t)`` of the switch, ``S(1) = 1/2``, to meet the true length at the outer fraction. Equal fractions denote a model without a - bridging window, whose table reads the true length and whose envelope is - the cutoff factor alone. + bridging window, whose table reads the true length, whose envelope is the + cutoff factor alone and whose switch is one. Returns ------- - tuple[torch.Tensor, torch.Tensor] - The envelope and the length the table reads, both with the shape of - ``radius``. + tuple[torch.Tensor, torch.Tensor, torch.Tensor] + The envelope, the length the table reads and the switch ``h(t)``, all + with the shape of ``radius``. """ if f_outer <= f_inner: - return _cutoff_factor(radius, rcut), radius + return _cutoff_factor(radius, rcut), radius, torch.ones_like(radius) width = f_outer - f_inner t = ((radius / contact - f_inner) / width).clamp(0.0, 1.0) switch = t**4 * (35.0 + t * (-84.0 + t * (70.0 - 20.0 * t))) rise = t**5 * (7.0 + t * (-14.0 + t * (10.0 - 2.5 * t))) clamped = contact * (window_midpoint(f_inner, f_outer) + width * rise) seen = torch.where(radius >= f_outer * contact, radius, clamped) - return _cutoff_factor(seen, rcut) * switch, seen + return _cutoff_factor(seen, rcut) * switch, seen, switch + + +def _source_gate( + switch: torch.Tensor, + row_switch: torch.Tensor, + keep: torch.Tensor, + source: torch.Tensor, + destination: torch.Tensor, + node_count: int, + exchange: Callable[[torch.Tensor], torch.Tensor] | None, +) -> torch.Tensor: + r"""Evaluate the leave-one-out source gate of every edge. + + A descriptor of several blocks with a bridging window mutes every edge that + an atom inside the frozen zone of a pair emits towards a third atom (see + ``compute_source_gates`` of DPA4): the gate of an edge :math:`j \to i` is + the product of the switches of every other pair of :math:`j`. The graph + holds both directions of every bond, so the row of :math:`j` holds every + pair of :math:`j`, and the totals of the rows, the sum of the logarithms + of the nonzero switches and the number of zero ones, are those of the + edges :math:`j` emits; ``exchange`` refreshes the totals of the halo rows, + which carry no edges, from their owners. An edge then removes its own + switch from the totals of its source. Masked edges contribute a switch of + one. + + The totals read ``row_switch``, the switch of every edge as an entry of the + row of its destination, whose values are those of ``switch``. A separately + differentiated copy separates the slope of the totals, which belongs to + the node of each row, from the slope of the switch of every edge itself. + + Parameters + ---------- + switch + Bridging switch of every edge with shape ``(E,)``. + row_switch + Bridging switch of every edge as the totals read it, shape ``(E,)``. + keep + One on the kept edges and zero on the masked ones, shape ``(E,)``. + source, destination + Source and destination node of every edge with shape ``(E,)``. + node_count + Number of nodes. + exchange + Halo exchange of a node set with halo rows, or ``None``. + + Returns + ------- + torch.Tensor + Gate of every edge with shape ``(E,)``. + """ + + def logarithms(value: torch.Tensor) -> torch.Tensor: + weight = value * keep + (1.0 - keep) + frozen = (weight <= 0.0).to(weight.dtype) + log_weight = torch.log( + torch.where(weight > 0.0, weight, torch.ones_like(weight)) + ) + return torch.stack((log_weight, frozen), dim=-1) + + totals = torch.zeros( + node_count, 2, dtype=switch.dtype, device=switch.device + ).index_add_(0, destination, logarithms(row_switch)) + if exchange is not None: + totals = exchange(totals) + others = totals[source] - logarithms(switch) + return torch.where( + others[:, 1] > 0.5, torch.zeros_like(switch), torch.exp(others[:, 0]) + ) def _half_gram(value: torch.Tensor) -> torch.Tensor: @@ -1463,6 +1503,9 @@ def _reference_descriptor( spin_pair: torch.Tensor | None = None, spin_type: torch.Tensor | None = None, edge_spin: torch.Tensor | None = None, + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, + row_edge_vec: torch.Tensor | None = None, ) -> torch.Tensor: """Reference implementation of the compressed DPA4C descriptor. @@ -1479,6 +1522,16 @@ def _reference_descriptor( every edge, which the neighbor families read in place of ``spin[source]``; with equal values the descriptor is the same, and the cotangent of the neighbor moments is resolved per edge. + + ``blocks_record`` holds the records of the further message-passing blocks + with shape ``(n_blocks - 1, width)`` (see + :func:`~deepmd.pt_expt.kernels.dpa4c.attention.build_block_artifacts`); + ``None`` or an empty tensor denotes a single block. ``exchange`` refreshes + the halo rows of a node feature from their owners before every further + block reads them, and is ``None`` for a graph without halo nodes. + ``row_edge_vec``, with the values of ``edge_vec``, is the edge geometry + that the switch totals of a source gate read (see :func:`_source_gate`); + ``None`` reads ``edge_vec`` itself. """ del destination_order, destination_row_ptr, canonical, coupling_meta compute = edge_vec.to(torch.float32) @@ -1499,10 +1552,22 @@ def _reference_descriptor( maskf = mask.to(compute.dtype) radii = contact_radius.to(compute.dtype) contact = radii[center_type] + radii[neighbor_type] - envelope, seen = _edge_envelope( + envelope, seen, switch = _edge_envelope( radius, contact, float(rcut), float(f_inner), float(f_outer) ) envelope = envelope * maskf + further_blocks = blocks_record is not None and blocks_record.numel() > 0 + if further_blocks and float(f_outer) > float(f_inner): + row_switch = switch + if row_edge_vec is not None: + row = row_edge_vec.to(torch.float32) + row_radius = torch.sqrt((row * row).sum(dim=-1) + float(eps) ** 2) + row_switch = _edge_envelope( + row_radius, contact, float(rcut), float(f_inner), float(f_outer) + )[2] + envelope = envelope * _source_gate( + switch, row_switch, maskf, source, destination, node_count, exchange + ) # === Step 2. Evaluate the ordered FiLM amplitude === tabulated = _table_lookup( @@ -1568,66 +1633,12 @@ def _reference_descriptor( * angular_norm ) - # === Step 4. Align, project, and contract the invariant readout === - width_one, width_two = profile.degree_channels[1], profile.degree_channels[2] - rank_one, rank_two = profile.ranks[0], profile.ranks[1] - aligned = list(blocks) - aligned[1] = blocks[1] @ readout_matrices[0, :width_one, :width_one] - aligned[2] = blocks[2] @ readout_matrices[2, :width_two, :width_two] - probes = list(aligned[1:]) - probes[0] = aligned[1] @ readout_matrices[4, :width_one, :rank_one] - probes[1] = aligned[2] @ readout_matrices[6, :width_two, :rank_two] - - vectors = probes[0].transpose(1, 2) - tensors = packed_l2_to_stf(probes[1].transpose(1, 2)) - tensor_vector = (tensors[:, :, None] @ vectors[:, None, :, :, None]).squeeze(-1) - parts: dict[int, torch.Tensor] = {} - for record in coupling_records(int(channels), profile.lmax)[0]: - degree_1, degree_2, degree_3 = record.degrees - start = record.nonzero_begin - components = coupling_entry[start : start + record.nonzero_count] - coupling = torch.zeros( - 2 * degree_1 + 1, - 2 * degree_2 + 1, - 2 * degree_3 + 1, - dtype=compute.dtype, - device=compute.device, - ) - coupling[ - components & 0xFF, - (components >> 8) & 0xFF, - (components >> 16) & 0xFF, - ] = coupling_value[start : start + record.nonzero_count].to(compute.dtype) - full = _contract_coupling( - coupling, - probes[degree_1 - 1], - probes[degree_2 - 1], - probes[degree_3 - 1], - ) - start = record.probe_begin - selection = coupling_entry[start : start + record.probe_count] - rank_2 = profile.ranks[degree_2 - 1] - rank_3 = profile.ranks[degree_3 - 1] - flat = ( - ((selection & 0xFF) * rank_2 + ((selection >> 8) & 0xFF)) * rank_3 - + ((selection >> 16) & 0xFF) - ).to(torch.long) - parts[record.coordinate] = full[:, flat] * coupling_value[ - start : start + record.probe_count - ].to(compute.dtype) - - parts[profile.bispectrum_base] = _closed_form_112( - vectors, - tensor_vector, - rank_one, - rank_two, - ) - parts[_closed_form_222_coordinate(profile)] = _closed_form_222(tensors) - - # === Step 5. Reduce and contract the native spin families === - spin_blocks: list[torch.Tensor] = [] + # === Step 4. Reduce the native spin families === + # The spin moments belong to the first block, and every further block + # keeps them. + spin_moments = None if has_spin: - magnitude, coordination, spin_vector, spin_tensor = _reference_spin_moments( + spin_moments = _reference_spin_moments( spin, spin[source] if edge_spin is None else edge_spin, spin_pair, @@ -1642,38 +1653,126 @@ def _reference_descriptor( angular_norm, node_count, ) - spin_blocks = [ - _half_gram(spin_vector), - # The quadrupole Gram omits its leading diagonal entry, the - # on-site self-term: the harmonic block is homogeneous, so - # |B_2(s)|^2 = |s|^4 makes that entry a per-type constant times - # the square of the vector block's own on-site self-term. - _half_gram(spin_tensor)[:, 1:], - # Cross Gram against the unaligned geometric degree-two moments. - # Both factors carry even spin order, so the product is - # admissible; with a unit direction it evaluates to the - # single-ion anisotropy sum over neighbors. - (spin_tensor.transpose(1, 2) @ blocks[2]).flatten(start_dim=1), - magnitude, - coordination, - ] - - # === Step 6. Assemble and calibrate the invariant output === - quartic = (tensor_vector * tensor_vector).sum(dim=-1).flatten(start_dim=1) - descriptor = torch.cat( - [ - blocks[0][:, 0, :], - *[_half_gram(block) for block in aligned[1:]], - *[parts[key] for key in sorted(parts)], - quartic, - *spin_blocks, - scalar_divisor, - angular_divisor, - type_embedding[atype], - ], - dim=-1, - ) - return (descriptor - output_mean[None, :]) * output_inv_std[None, :] + center_type_embedding = type_embedding[atype] + + def readout(moments: list[torch.Tensor]) -> torch.Tensor: + """Contract the moments of one block into its calibrated invariants.""" + # === Align, project, and contract the invariant readout === + width_one, width_two = profile.degree_channels[1], profile.degree_channels[2] + rank_one, rank_two = profile.ranks[0], profile.ranks[1] + aligned = list(moments) + aligned[1] = moments[1] @ readout_matrices[0, :width_one, :width_one] + aligned[2] = moments[2] @ readout_matrices[2, :width_two, :width_two] + probes = list(aligned[1:]) + probes[0] = aligned[1] @ readout_matrices[4, :width_one, :rank_one] + probes[1] = aligned[2] @ readout_matrices[6, :width_two, :rank_two] + + vectors = probes[0].transpose(1, 2) + tensors = packed_l2_to_stf(probes[1].transpose(1, 2)) + tensor_vector = (tensors[:, :, None] @ vectors[:, None, :, :, None]).squeeze(-1) + parts: dict[int, torch.Tensor] = {} + for record in coupling_records(int(channels), profile.lmax)[0]: + degree_1, degree_2, degree_3 = record.degrees + start = record.nonzero_begin + components = coupling_entry[start : start + record.nonzero_count] + coupling = torch.zeros( + 2 * degree_1 + 1, + 2 * degree_2 + 1, + 2 * degree_3 + 1, + dtype=compute.dtype, + device=compute.device, + ) + coupling[ + components & 0xFF, + (components >> 8) & 0xFF, + (components >> 16) & 0xFF, + ] = coupling_value[start : start + record.nonzero_count].to(compute.dtype) + full = _contract_coupling( + coupling, + probes[degree_1 - 1], + probes[degree_2 - 1], + probes[degree_3 - 1], + ) + start = record.probe_begin + selection = coupling_entry[start : start + record.probe_count] + rank_2 = profile.ranks[degree_2 - 1] + rank_3 = profile.ranks[degree_3 - 1] + flat = ( + ((selection & 0xFF) * rank_2 + ((selection >> 8) & 0xFF)) * rank_3 + + ((selection >> 16) & 0xFF) + ).to(torch.long) + parts[record.coordinate] = full[:, flat] * coupling_value[ + start : start + record.probe_count + ].to(compute.dtype) + + parts[profile.bispectrum_base] = _closed_form_112( + vectors, + tensor_vector, + rank_one, + rank_two, + ) + parts[_closed_form_222_coordinate(profile)] = _closed_form_222(tensors) + + # === Contract the native spin families === + spin_blocks: list[torch.Tensor] = [] + if spin_moments is not None: + magnitude, coordination, spin_vector, spin_tensor = spin_moments + spin_blocks = [ + _half_gram(spin_vector), + # The quadrupole Gram omits its leading diagonal entry, the + # on-site self-term: the harmonic block is homogeneous, so + # |B_2(s)|^2 = |s|^4 makes that entry a per-type constant + # times the square of the vector block's own on-site + # self-term. + _half_gram(spin_tensor)[:, 1:], + # Cross Gram against the unaligned geometric degree-two + # moments. Both factors carry even spin order, so the product + # is admissible; with a unit direction it evaluates to the + # single-ion anisotropy sum over neighbors. + (spin_tensor.transpose(1, 2) @ moments[2]).flatten(start_dim=1), + magnitude, + coordination, + ] + + # === Assemble and calibrate the invariant output === + quartic = (tensor_vector * tensor_vector).sum(dim=-1).flatten(start_dim=1) + descriptor = torch.cat( + [ + moments[0][:, 0, :], + *[_half_gram(block) for block in aligned[1:]], + *[parts[key] for key in sorted(parts)], + quartic, + *spin_blocks, + scalar_divisor, + angular_divisor, + center_type_embedding, + ], + dim=-1, + ) + return (descriptor - output_mean[None, :]) * output_inv_std[None, :] + + # === Step 5. Run the further message-passing blocks === + moments = blocks + if blocks_record is not None and blocks_record.numel() > 0: + layout = block_layout(profile) + for record in blocks_record: + moments = further_block_moments( + record, + layout, + blocks, + moments, + readout(moments), + amplitude, + basis, + envelope, + radius, + source, + destination, + scalar_divisor, + angular_divisor, + exchange, + ) + return readout(moments) def _reference_spin_moments( @@ -1939,8 +2038,14 @@ def _portable_inputs(args: tuple) -> tuple: def _reference_forward( edge_vec: torch.Tensor, *args: Any, + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: - """CPU custom-op implementation returning descriptor and opaque state.""" + """Return the reference descriptor and an opaque state of the operator inputs. + + ``blocks_record`` and ``exchange`` are those of + :func:`_reference_descriptor`. + """ args = (edge_vec, *_portable_inputs(args)) descriptor = _reference_descriptor( *args[:16], @@ -1948,6 +2053,8 @@ def _reference_forward( spin=args[16], spin_pair=args[17], spin_type=args[18], + blocks_record=blocks_record, + exchange=exchange, ) profile = descriptor_profile( int(args[9].shape[1]), @@ -2076,13 +2183,22 @@ def _backward_fake( ) -def _reference_backward( +def _reference_cotangents( descriptor_gradient: torch.Tensor, state: torch.Tensor, edge_vec: torch.Tensor, *args: Any, -) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: - """CPU custom-op backward returning the coordinate and magnetic cotangents. + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Return the reference coordinate and magnetic cotangents of the descriptor. + + The coordinate cotangent of every edge comes in two parts that share the + vector of the edge and add up to its cotangent. The switch totals of a + source gate read the pairs of every row as the edges the node of the row + emits (see :func:`_source_gate`), so their part, the second result, + belongs to the destination of each edge, and the first part belongs to + its source. The second part is zero without a source gate. The magnetic cotangent is split as in the device operator, which splits it because a destination-major scan does not own the source of an edge: the @@ -2094,7 +2210,9 @@ def _reference_backward( A non-empty pair table adds the analytical pair potential: its energy, weighted by the per-node cotangent ``pair_seed``, joins the differentiated objective, so the coordinate cotangent carries the slope of the pair term, - and the node energies of the term are returned as the fourth result. + and the node energies of the term are returned as the fifth result. + ``blocks_record`` and ``exchange`` are those of + :func:`_reference_descriptor`. """ del state args = _portable_inputs(args) @@ -2102,6 +2220,7 @@ def _reference_backward( pair_table, pair_seed = args[_PAIR_TABLE_SLOT:] has_spin = spin.ndim == 2 value = edge_vec.detach().clone().requires_grad_(True) + row_value = edge_vec.detach().clone().requires_grad_(True) moment = spin.detach().clone().requires_grad_(has_spin) edge_moment = ( spin.detach()[args[0][0].to(torch.long)].requires_grad_(True) @@ -2118,6 +2237,9 @@ def _reference_backward( spin_pair=args[16], spin_type=args[17], edge_spin=edge_moment, + blocks_record=blocks_record, + exchange=exchange, + row_edge_vec=row_value, ) objective = (descriptor * descriptor_gradient.to(descriptor.dtype)).sum() if pair_table.numel(): @@ -2132,18 +2254,44 @@ def _reference_backward( objective = objective + (pair_energy[:, 0] * pair_seed.reshape(-1)).sum() gradients = torch.autograd.grad( objective, - (value, moment, edge_moment) if has_spin else (value,), + (value, row_value, moment, edge_moment) if has_spin else (value, row_value), + materialize_grads=True, ) return ( gradients[0].to(edge_vec.dtype), - gradients[1] if has_spin else edge_vec.new_empty((0,), dtype=torch.float32), - gradients[2].to(edge_vec.dtype) + gradients[1].to(edge_vec.dtype), + gradients[2] if has_spin else edge_vec.new_empty((0,), dtype=torch.float32), + gradients[3].to(edge_vec.dtype) if has_spin else edge_vec.new_empty((0,), dtype=torch.float32), pair_energy.detach(), ) +def _reference_backward( + descriptor_gradient: torch.Tensor, + state: torch.Tensor, + edge_vec: torch.Tensor, + *args: Any, + blocks_record: torch.Tensor | None = None, + exchange: Callable[[torch.Tensor], torch.Tensor] | None = None, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Return the reference cotangents in the layout of the backward operator. + + The results are those of :func:`_reference_cotangents` with the two parts + of the coordinate cotangent of every edge added up. + """ + edge, row, *rest = _reference_cotangents( + descriptor_gradient, + state, + edge_vec, + *args, + blocks_record=blocks_record, + exchange=exchange, + ) + return (edge + row, *rest) + + #: Position of the per-node magnetic moment among the operator inputs, and its #: position among the tensors :func:`_setup_context` saves, which lead with the #: opaque state. diff --git a/deepmd/pt_expt/kernels/dpa4c/profile.py b/deepmd/pt_expt/kernels/dpa4c/profile.py new file mode 100644 index 0000000000..db95c6ab71 --- /dev/null +++ b/deepmd/pt_expt/kernels/dpa4c/profile.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Structural widths shared by compressed DPA4C operators.""" + +from dataclasses import ( + dataclass, +) + + +@dataclass(frozen=True) +class DescriptorProfile: + r"""Describe every width the compiled operator derives from its inputs. + + Attributes + ---------- + channels + Scalar degree-zero width :math:`C_0`. + lmax + Maximum angular degree. + degree_channels + Channel width of each degree from zero through ``lmax``. + ranks + Bispectrum probe rank of each degree from one through ``lmax``. + moment_width + Flat moment width :math:`S=\sum_\ell(2\ell+1)C_\ell`. + output_width + Invariant descriptor width consumed by the fitting network. + gram_base + Descriptor coordinate of the first degree-one Gram entry. + bispectrum_base + Descriptor coordinate of the first bispectrum entry. + spin_width + Width of the trailing native-spin invariant block. + basis + Width of the low-rank expansion of the scalar-only channels, zero for + a profile that admits no expansion. + """ + + channels: int + lmax: int + degree_channels: tuple[int, ...] + ranks: tuple[int, ...] + moment_width: int + output_width: int + gram_base: int + bispectrum_base: int + spin_channels: int + spin_width: int + basis: int + + @property + def state_width(self) -> int: + """Return the saved-state width: the moments plus both normalizers.""" + return self.moment_width + 2 + + @property + def has_spin(self) -> bool: + """Return whether the compiled profile carries the spin families.""" + return self.spin_channels > 0 + + @property + def spin_slice(self) -> slice: + """Return the descriptor columns holding the spin invariants. + + The layout closes with the spin invariants, the two moment divisors + and the center type tail, so the block is addressed from the end and + is empty for a spin-free profile. + """ + stop = self.output_width - 2 - self.degree_channels[0] + return slice(stop - self.spin_width, stop) diff --git a/deepmd/pt_expt/kernels/fitting_routes.py b/deepmd/pt_expt/kernels/fitting_routes.py index 354668107b..8d8d7bfac9 100644 --- a/deepmd/pt_expt/kernels/fitting_routes.py +++ b/deepmd/pt_expt/kernels/fitting_routes.py @@ -26,7 +26,11 @@ run size at which the winner changes. Each sample times the compared routes on the canonical graph of a periodic bulk system of exactly the run size of atoms, as replays of a captured CUDA graph of the whole operator, which is how -LAMMPS evaluates it. +LAMMPS evaluates it. For a descriptor of several message-passing blocks the +operator is that of its first block: the routes change no further block, +whose scans take the same time on every route and most of the time of the +operator, so the measurement times what it compares at a fraction of the +cost. A sample times the routes in two ways. Within each capture of the operator the replays of the routes alternate, so that every route runs at the clocks of a @@ -282,9 +286,10 @@ def _bulk_graph(rcut: float, node_count: int, device: torch.device) -> Any: class _Bench: """Times the fused operator of one model on synthetic bulk systems. - The operator is that without a long-range module, with the descriptor of - the model and the network ``fitting`` with its atomic bias ``atom_bias``, - the energy fitting or a charge network, in place of the energy fitting. + The operator is that without a long-range module, with the first + message-passing block of the descriptor of the model and the network + ``fitting`` with its atomic bias ``atom_bias``, the energy fitting or a + charge network, in place of the energy fitting. The bench keeps four counters, which :func:`_tune_network` logs: - ``samples``, the samples of run sizes that it times, those of the @@ -309,7 +314,10 @@ def __init__( import copy learned, pair_potential = model.atomic_model.fused_decomposition() + # A copy of the descriptor without its further blocks, which the + # operator evaluates as one block. self.descriptor = copy.deepcopy(learned.descriptor).to(device).eval() + self.descriptor.attentions = torch.nn.ModuleList() self.fitting = copy.deepcopy(fitting).to(device).eval() self.atom_bias = atom_bias.to(device) self.pair_table = ( diff --git a/deepmd/pt_expt/long_range/latent_charge.py b/deepmd/pt_expt/long_range/latent_charge.py index cadd860d50..8059d11c8b 100644 --- a/deepmd/pt_expt/long_range/latent_charge.py +++ b/deepmd/pt_expt/long_range/latent_charge.py @@ -52,12 +52,15 @@ def _pair_kernel( return self.kernel.evaluate(r_sq, coefficients) def operator_eligible(self) -> bool: - """Whether :meth:`energy_force_from_coord` evaluates this module. + """Whether :meth:`energy_force_from_coord` evaluates this configuration. The operator evaluates the kernels, channel counts and B-spline orders it is instantiated for. The compact lower that calls it reads no frame input: the charges depend on the descriptor alone, and a constrained - channel sums to zero or to the total charge of a folded charge state. + channel sums to zero or to the total charge of a folded charge state, + so a module that reads the charge state of each frame + (:meth:`uses_charge_spin`) is evaluated once the compression of the + model has folded it. """ from deepmd.pt_expt.kernels.long_range import ( MAX_CHANNELS, @@ -73,7 +76,6 @@ def operator_eligible(self) -> bool: and self.pme_order <= MAX_ORDER and self.charge_net.numb_fparam == 0 and self.charge_net.numb_aparam == 0 - and not self.uses_charge_spin() ) def operator_constraint( diff --git a/deepmd/pt_expt/model/ener_model.py b/deepmd/pt_expt/model/ener_model.py index f18d3e33fc..e749ad57d6 100644 --- a/deepmd/pt_expt/model/ener_model.py +++ b/deepmd/pt_expt/model/ener_model.py @@ -153,6 +153,8 @@ def forward_lower_canonical_graph( coord: torch.Tensor | None = None, communicator: torch.Tensor | None = None, box: torch.Tensor | None = None, + halo_send: torch.Tensor | None = None, + halo_swaps: torch.Tensor | None = None, ) -> dict[str, torch.Tensor]: """Evaluate an eligible compressed canonical deployment graph. @@ -189,10 +191,11 @@ def forward_lower_canonical_graph( Node positions with shape ``(N, 3)`` in Å, float64, for a model with a long-range module; ``None`` otherwise. communicator - For a model with a long-range module, the address of the MPI_Comm - handle of a frame decomposed into domains, one per rank, as an - int64 CPU tensor of one element, whose owned nodes are then those - of one domain; zero or ``None`` for a complete frame. + For a model with a long-range module or with further + message-passing blocks, the address of the MPI_Comm handle of a + frame decomposed into domains, one per rank, as an int64 CPU + tensor of one element, whose owned nodes are then those of one + domain; zero or ``None`` for a complete frame. box For a model with a long-range module, the cells of the frames with shape ``(nf, 9)``, float64 on the CPU, the rows of every @@ -200,6 +203,11 @@ def forward_lower_canonical_graph( complete non-periodic frame, and ``None`` non-periodic frames. The halo nodes of a periodic frame are images of its owned nodes. + halo_send, halo_swaps + For a model with further message-passing blocks, the send list and + the swap table of the border plan of a single frame (see + :class:`~deepmd.pt_expt.utils.canonical_graph.BorderPlan`), with + ``communicator``; ``None`` for a frame without halo nodes. Returns ------- @@ -215,14 +223,25 @@ def forward_lower_canonical_graph( from deepmd.pt_expt.kernels.dpa4c.canonical import ( canonical_model_eligible as dpa4c_canonical_eligible, ) + from deepmd.pt_expt.kernels.dpa4c.canonical import ( + canonical_model_unsupported_reason as dpa4c_canonical_unsupported, + ) from deepmd.pt_expt.kernels.dpa4c.canonical import ( dpa4c_canonical_compress_energy_force, ) from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, CanonicalGraph, validate_canonical_graph_shapes, ) + if (halo_send is None) != (halo_swaps is None): + raise ValueError( + "the send list and the swap table of a border plan come together" + ) + reason = dpa4c_canonical_unsupported(self) + if reason is not None: + raise ValueError(reason) use_dpa4c = dpa4c_canonical_eligible(self) if not use_dpa4c and not dpa1_canonical_eligible(self): raise ValueError("model is not eligible for compact canonical deployment") @@ -240,6 +259,15 @@ def forward_lower_canonical_graph( descriptor = learned.descriptor fitting = learned.fitting_net atom_bias = fused_atom_bias(self.atomic_model, learned) + border = ( + None + if halo_send is None + else BorderPlan( + send_nodes=halo_send, + swaps=halo_swaps, + communicator=communicator, + ) + ) def fused_graph() -> CanonicalGraph: # A program without the per-atom virial declines it with the @@ -285,9 +313,16 @@ def fused_graph() -> CanonicalGraph: atom_bias, fitting_routes(fitting), fitting_routes(learned.long_range.charge_net), + border, ) ) else: + if border is not None: + raise ValueError( + "a border plan serves further message-passing blocks, " + "which the composition of long-range operators does " + "not evaluate" + ) atype, output_mask = self.atomic_model._prepare_graph_nodes( n_node, n_local, @@ -325,6 +360,7 @@ def fused_graph() -> CanonicalGraph: spin, None if pair_potential is None else pair_potential.pair_table, fitting_routes(fitting), + border, ) ) else: @@ -383,12 +419,18 @@ def forward_lower_canonical_graph_exportable( coord: torch.Tensor | None = None, communicator: torch.Tensor | None = None, box: torch.Tensor | None = None, + halo_send: torch.Tensor | None = None, + halo_swaps: torch.Tensor | None = None, *, do_atomic_virial: bool, **make_fx_kwargs: Any, ) -> torch.nn.Module: """Trace the compact canonical deployment forward with ``make_fx``. + The traced module takes the eight graph tensors, then the inputs that + the model reads in the order ``coord``, ``communicator``, ``box``, + ``halo_send``, ``halo_swaps``. + Parameters ---------- atype, n_node, n_local, source, edge_vec @@ -399,8 +441,11 @@ def forward_lower_canonical_graph_exportable( For a model with a long-range module, sample node positions with shape ``(N, 3)``, float64, a sample communicator, an int64 CPU tensor of one element, and sample cells with shape ``(nf, 9)``, - float64 on the CPU, which the traced module then takes as its - ninth to eleventh inputs; ``None`` otherwise. + float64 on the CPU; ``None`` otherwise. + halo_send, halo_swaps + For a model with further message-passing blocks, a sample border + plan, with the sample ``communicator``, which a model that has a + long-range module as well reads once; ``None`` otherwise. do_atomic_virial Whether the traced output includes per-node virial. **make_fx_kwargs @@ -409,47 +454,70 @@ def forward_lower_canonical_graph_exportable( Returns ------- torch.nn.Module - Traced compact deployment module of eight inputs, or eleven with - the node positions, the communicator and the cells. + Traced compact deployment module of the eight graph inputs, + followed by those of ``coord``, ``communicator``, ``box``, + ``halo_send`` and ``halo_swaps`` that the model reads. """ model = self - if not (coord is None) == (communicator is None) == (box is None): + has_long_range = coord is not None + has_border = halo_send is not None + if ( + (box is not None) != has_long_range + or (halo_swaps is not None) != has_border + or (communicator is not None) != (has_long_range or has_border) + ): raise ValueError( - "the compact lower of a model with a long-range module takes " - "the node positions, the communicator and the cells together" + "the compact lower takes the node positions and the cells of a " + "long-range module together, the send list and the swap table " + "of the border plan of further message-passing blocks " + "together, and the communicator with either" ) - if coord is not None: + def lower( + *graph: torch.Tensor, **inputs: torch.Tensor + ) -> dict[str, torch.Tensor]: + return model.forward_lower_canonical_graph( + *graph, do_atomic_virial=do_atomic_virial, **inputs + ) - def fn_long_range( - atype: torch.Tensor, - n_node: torch.Tensor, - n_local: torch.Tensor, - source: torch.Tensor, - edge_vec: torch.Tensor, - destination_row_ptr: torch.Tensor, - source_row_ptr: torch.Tensor, - source_order: torch.Tensor, - coord: torch.Tensor, - communicator: torch.Tensor, - box: torch.Tensor, - ) -> dict[str, torch.Tensor]: - return model.forward_lower_canonical_graph( - atype, - n_node, - n_local, - source, - edge_vec, - destination_row_ptr, - source_row_ptr, - source_order, - do_atomic_virial=do_atomic_virial, - coord=coord, - communicator=communicator, - box=box, - ) + # Every input of the traced module takes the name of a parameter of + # the traced function, so each combination of the inputs that the + # model reads after the graph has a function of its own. + def fn( + atype: torch.Tensor, + n_node: torch.Tensor, + n_local: torch.Tensor, + source: torch.Tensor, + edge_vec: torch.Tensor, + destination_row_ptr: torch.Tensor, + source_row_ptr: torch.Tensor, + source_order: torch.Tensor, + ) -> dict[str, torch.Tensor]: + return lower( + atype, + n_node, + n_local, + source, + edge_vec, + destination_row_ptr, + source_row_ptr, + source_order, + ) - return make_fx(fn_long_range, **make_fx_kwargs)( + def fn_long_range( + atype: torch.Tensor, + n_node: torch.Tensor, + n_local: torch.Tensor, + source: torch.Tensor, + edge_vec: torch.Tensor, + destination_row_ptr: torch.Tensor, + source_row_ptr: torch.Tensor, + source_order: torch.Tensor, + coord: torch.Tensor, + communicator: torch.Tensor, + box: torch.Tensor, + ) -> dict[str, torch.Tensor]: + return lower( atype, n_node, n_local, @@ -458,12 +526,12 @@ def fn_long_range( destination_row_ptr, source_row_ptr, source_order, - coord, - communicator, - box, + coord=coord, + communicator=communicator, + box=box, ) - def fn( + def fn_border( atype: torch.Tensor, n_node: torch.Tensor, n_local: torch.Tensor, @@ -472,8 +540,11 @@ def fn( destination_row_ptr: torch.Tensor, source_row_ptr: torch.Tensor, source_order: torch.Tensor, + communicator: torch.Tensor, + halo_send: torch.Tensor, + halo_swaps: torch.Tensor, ) -> dict[str, torch.Tensor]: - return model.forward_lower_canonical_graph( + return lower( atype, n_node, n_local, @@ -482,10 +553,52 @@ def fn( destination_row_ptr, source_row_ptr, source_order, - do_atomic_virial=do_atomic_virial, + communicator=communicator, + halo_send=halo_send, + halo_swaps=halo_swaps, ) - return make_fx(fn, **make_fx_kwargs)( + def fn_long_range_border( + atype: torch.Tensor, + n_node: torch.Tensor, + n_local: torch.Tensor, + source: torch.Tensor, + edge_vec: torch.Tensor, + destination_row_ptr: torch.Tensor, + source_row_ptr: torch.Tensor, + source_order: torch.Tensor, + coord: torch.Tensor, + communicator: torch.Tensor, + box: torch.Tensor, + halo_send: torch.Tensor, + halo_swaps: torch.Tensor, + ) -> dict[str, torch.Tensor]: + return lower( + atype, + n_node, + n_local, + source, + edge_vec, + destination_row_ptr, + source_row_ptr, + source_order, + coord=coord, + communicator=communicator, + box=box, + halo_send=halo_send, + halo_swaps=halo_swaps, + ) + + traced = { + (False, False): fn, + (True, False): fn_long_range, + (False, True): fn_border, + (True, True): fn_long_range_border, + }[(has_long_range, has_border)] + # The inputs that the model reads after the graph, in the order of the + # compact lower. + trailing = (coord, communicator, box, halo_send, halo_swaps) + return make_fx(traced, **make_fx_kwargs)( atype, n_node, n_local, @@ -494,6 +607,7 @@ def fn( destination_row_ptr, source_row_ptr, source_order, + *(value for value in trailing if value is not None), ) def forward( diff --git a/deepmd/pt_expt/model/native_spin_model.py b/deepmd/pt_expt/model/native_spin_model.py index 1557f20fa4..72daf2d55d 100644 --- a/deepmd/pt_expt/model/native_spin_model.py +++ b/deepmd/pt_expt/model/native_spin_model.py @@ -316,6 +316,9 @@ def forward_lower_canonical_graph_exportable( source_row_ptr: torch.Tensor, source_order: torch.Tensor, spin: torch.Tensor, + communicator: torch.Tensor | None = None, + halo_send: torch.Tensor | None = None, + halo_swaps: torch.Tensor | None = None, *, do_atomic_virial: bool, **make_fx_kwargs: Any, @@ -325,8 +328,10 @@ def forward_lower_canonical_graph_exportable( THIS METHOD OWNS the positional ``.pt2`` ABI for compact canonical spin models (mirrored verbatim by the C++ / serialization seams): ``spin`` sits at index 8, directly after the dual-CSR block, which is - the same placement rule the graph ABI uses at index 10. The compact ABI - has no conditional tail, so index 8 is the last slot. + the same placement rule the graph ABI uses at index 10. A model with + further message-passing blocks takes the communicator and the border + plan at indices 9 to 11, and the lower of any other model ends at + index 8. The magnetic force is a value here rather than an autograd result: the fused operator closes the on-site part in its node kernel and @@ -342,6 +347,9 @@ def forward_lower_canonical_graph_exportable( Compact dual-CSR topology. spin ``(N, 3)`` per-node moment. Ghost rows carry their owner's moment. + communicator, halo_send, halo_swaps + For a model with further message-passing blocks, a sample + communicator and border plan, given together; ``None`` otherwise. do_atomic_virial Whether the traced output includes per-node virial. **make_fx_kwargs @@ -350,10 +358,68 @@ def forward_lower_canonical_graph_exportable( Returns ------- torch.nn.Module - Traced nine-input compact deployment module whose output dict adds + Traced compact deployment module of nine inputs, or twelve with + the communicator and the border plan, whose output dict adds ``force_mag`` and ``mask_mag`` to the spin-free key set. """ model = self + border = (communicator, halo_send, halo_swaps) + if any(value is None for value in border) and any( + value is not None for value in border + ): + raise ValueError( + "the compact spin lower takes the communicator and the border " + "plan of further message-passing blocks together" + ) + + if halo_send is not None: + + def fn_message_passing( + atype: torch.Tensor, + n_node: torch.Tensor, + n_local: torch.Tensor, + source: torch.Tensor, + edge_vec: torch.Tensor, + destination_row_ptr: torch.Tensor, + source_row_ptr: torch.Tensor, + source_order: torch.Tensor, + spin: torch.Tensor, + communicator: torch.Tensor, + halo_send: torch.Tensor, + halo_swaps: torch.Tensor, + ) -> dict[str, torch.Tensor]: + result = model.forward_lower_canonical_graph( + atype, + n_node, + n_local, + source, + edge_vec, + destination_row_ptr, + source_row_ptr, + source_order, + do_atomic_virial=do_atomic_virial, + spin=spin, + communicator=communicator, + halo_send=halo_send, + halo_swaps=halo_swaps, + ) + result["mask_mag"] = model._spin_active_mask(atype) + return result + + return make_fx(fn_message_passing, **make_fx_kwargs)( + atype, + n_node, + n_local, + source, + edge_vec, + destination_row_ptr, + source_row_ptr, + source_order, + spin, + communicator, + halo_send, + halo_swaps, + ) def fn( atype: torch.Tensor, diff --git a/deepmd/pt_expt/utils/canonical_graph.py b/deepmd/pt_expt/utils/canonical_graph.py index c8afd7d63a..c0597e6e35 100644 --- a/deepmd/pt_expt/utils/canonical_graph.py +++ b/deepmd/pt_expt/utils/canonical_graph.py @@ -8,10 +8,14 @@ from dataclasses import ( dataclass, ) +from itertools import ( + pairwise, +) from typing import ( TYPE_CHECKING, ) +import numpy as np import torch if TYPE_CHECKING: @@ -96,6 +100,136 @@ class CanonicalGraph: source_order: torch.Tensor +@dataclass(frozen=True) +class BorderPlan: + """Store the border plan of the node set of one domain of a decomposed frame. + + The node set holds the owned nodes first, then the halo nodes, images of + atoms that other swaps of a LAMMPS brick decomposition deliver. A model + whose further message-passing blocks read features of the edge sources + refreshes the halo rows of those features from their owners with this + plan (``source/op/pt/border_exchange.h``), and evaluates the owned nodes + alone. A node set without halo nodes carries a plan without swaps. + + Parameters + ---------- + send_nodes + Nodes that the swaps send, the swaps concatenated in order, with shape + ``(M,)``, int32, on the device of the graph; entries past the rows of + the swaps are unused. + swaps + Swap table with shape ``(nswap, 5)``, int32, on the CPU: the rank that + swap ``s`` sends to, the rank it receives from, the counts of the rows + it sends and receives, and the first halo row it receives into. + communicator + Address of the MPI_Comm handle of the decomposition, an int64 CPU + tensor of one element, zero for a single process. + """ + + send_nodes: torch.Tensor + swaps: torch.Tensor + communicator: torch.Tensor + + @classmethod + def single_domain(cls, device: torch.device) -> BorderPlan: + """Return the plan of a node set without halo nodes.""" + return cls( + send_nodes=torch.zeros(2, dtype=torch.int32, device=device), + swaps=torch.zeros(0, 5, dtype=torch.int32, device="cpu"), + communicator=torch.zeros(1, dtype=torch.int64, device="cpu"), + ) + + +def validate_reciprocal_canonical_graph(graph: CanonicalGraph) -> None: + """Check reverse edges of a complete, single-domain graph at construction. + + Every physical edge must have a reverse edge with opposite displacement. + Periodic images sharing a node pair are matched one-to-one within the + displacement tolerance. Lexicographic displacement order pairs reciprocal + images on the graph device. Groups that do not match within tolerance in + this order are compacted before host-side matching. Storage guards are + ignored. This check synchronizes the device and belongs at graph + construction, not inside a captured inference operator. A partitioned + graph cannot be checked locally. + """ + device = graph.source.device + destination = torch.repeat_interleave( + torch.arange( + graph.destination_row_ptr.numel() - 1, dtype=torch.int64, device=device + ), + graph.destination_row_ptr.diff(), + ) + count = destination.numel() + source = canonical_index_words(graph.source)[:count].to(torch.int64) + vector = graph.edge_vec[:count] + + def ordered( + center: torch.Tensor, neighbor: torch.Tensor, order: torch.Tensor + ) -> torch.Tensor: + """Group endpoints while preserving the supplied displacement order.""" + for column in (neighbor, center): + order = order[torch.argsort(column[order], stable=True)] + return order + + # Negating every displacement reverses its lexicographic order. One + # geometry ordering therefore serves both directions, including self-images. + geometry_order = torch.arange(count, dtype=torch.int64, device=device) + for axis in (2, 1, 0): + geometry_order = geometry_order[ + torch.argsort(vector[geometry_order, axis], stable=True) + ] + forward = ordered(destination, source, geometry_order) + reverse = ordered(source, destination, geometry_order.flip(0)) + message = ( + "multi-block DPA4C requires a globally bidirectional graph: " + "each edge must have a reverse edge with opposite displacement" + ) + same_pair = (destination[forward] == source[reverse]) & ( + source[forward] == destination[reverse] + ) + actual, expected = vector[forward], -vector[reverse] + aligned = torch.isclose(actual, expected, rtol=2e-6, atol=2e-6).all(dim=1) + if bool((same_pair & aligned).all()): + return + if not bool(same_pair.all()): + raise ValueError(message) + # A prefix count identifies groups with any mismatch. Keep every edge of + # those groups for one-to-one matching, without transferring accepted groups. + changes = (destination[forward][1:] != destination[forward][:-1]) | ( + source[forward][1:] != source[forward][:-1] + ) + ends = torch.cat( + (torch.nonzero(changes).flatten() + 1, source.new_full((1,), count)) + ) + starts = torch.cat((source.new_zeros(1), ends[:-1])) + sizes = ends - starts + prefix = torch.cat((source.new_zeros(1), (~aligned).to(torch.int64).cumsum(0))) + pending = prefix[ends] != prefix[starts] + selected = torch.repeat_interleave(pending, sizes, output_size=count) + actual = actual[selected].detach().cpu().numpy() + expected = expected[selected].detach().cpu().numpy() + starts = np.cumsum([0, *sizes[pending].cpu().tolist()]) + for begin, end in pairwise(starts): + adjacent = np.isclose( + actual[begin:end, None], expected[None, begin:end], rtol=2e-6, atol=2e-6 + ).all(axis=-1) + owner = [-1] * (end - begin) + + def augment(node: int, seen: set[int]) -> bool: + """Reassign images along a path to an unmatched reverse image.""" + for target in np.flatnonzero(adjacent[node]): + if target in seen: + continue + seen.add(target) + if owner[target] < 0 or augment(owner[target], seen): + owner[target] = node + return True + return False + + if not all(augment(node, set()) for node in range(end - begin)): + raise ValueError(message) + + def validate_canonical_graph_shapes( graph: CanonicalGraph, node_count: int, @@ -311,4 +445,5 @@ def canonical_graph_from_pairs( "canonical_index_dtype", "canonical_index_words", "validate_canonical_graph_shapes", + "validate_reciprocal_canonical_graph", ] diff --git a/deepmd/pt_expt/utils/serialization.py b/deepmd/pt_expt/utils/serialization.py index c1f7a238fd..3f88d0cc7a 100644 --- a/deepmd/pt_expt/utils/serialization.py +++ b/deepmd/pt_expt/utils/serialization.py @@ -222,9 +222,11 @@ def _needs_with_comm_artifact( graph lower carries a real per-layer ``border_op`` exchange, but its dense (nlist) lower's adapter raises on ``comm_dict``. ``lower_kind`` selects which lower is being traced so the gate can consult the - per-lower capability instead of assuming both lowers agree. Non-graph - kinds additionally check ``dense_lower_supports_comm()`` (``True`` for + per-lower capability instead of assuming both lowers agree. The dense + lower checks ``dense_lower_supports_comm()`` (``True`` for dpa2/dpa3, whose dense lower is the production multi-rank path). + Compact canonical lowers never use a separate with-comm artifact; the + multi-block DPA4C lower carries halo exchange in its main ABI. Native spin participates on the GRAPH lower, matching pt's ``SeZMModel.supports_edge_parallel`` (which ``SeZMNativeSpinModel`` does @@ -239,8 +241,8 @@ def _needs_with_comm_artifact( model : torch.nn.Module The wrapped pt_expt model. lower_kind : str - Which lower is being traced/frozen: ``"graph"`` or ``"nlist"`` - (dense). Defaults to ``"nlist"``. + Which lower is being traced/frozen: ``"graph"``, ``"nlist"`` (dense), + or a compact canonical kind. Defaults to ``"nlist"``. Returns ------- @@ -251,6 +253,9 @@ def _needs_with_comm_artifact( NativeSpinModelKind, ) + if lower_kind not in ("graph", "nlist"): + return False + # Cross-backend family test: the dpmodel and pt_expt concrete classes # are parallel factory products with no subclass relation, so the shared # marker base -- not a concrete class -- is the membership check. @@ -267,8 +272,7 @@ def _needs_with_comm_artifact( return False if lower_kind == "graph": return True - # Non-graph kinds trace the DENSE with-comm wrapper; a model whose dense - # lower has no comm implementation (DPA4) must not emit a dead artifact. + # The dense wrapper requires its own cross-rank communication contract. return bool(atomic_model.dense_lower_supports_comm()) @@ -891,16 +895,24 @@ def build_synthetic_canonical_graph_inputs( device: torch.device, want_spin: bool = False, want_long_range: bool = False, + want_border: bool = False, + border_sizes: tuple[int, int] = (3, 2), ) -> tuple[torch.Tensor, ...]: """Build compact canonical trace inputs for compressed CUDA descriptors. - ``want_spin`` appends the per-node moment at slot 8, the last slot of the - compact ABI, matching - :meth:`~deepmd.pt_expt.model.native_spin_model.NativeSpinEnergyModel.forward_lower_canonical_graph_exportable`. - ``want_long_range`` appends the inputs that the compact lower of a model - with a long-range module reads: the float64 node positions at slot 8, the - int64 communicator, a CPU tensor of one element, at slot 9, and the - float64 cells of the frames, a CPU tensor of shape ``(nf, 9)``, at slot 10. + The inputs that follow the eight graph tensors are those that the compact + lower of the model reads, in this order: the per-node moment of a + native-spin model (``want_spin``), matching + :meth:`~deepmd.pt_expt.model.native_spin_model.NativeSpinEnergyModel.forward_lower_canonical_graph_exportable`; + the float64 node positions of a model with a long-range module + (``want_long_range``); the int64 communicator, a CPU tensor of one + element, of a model with a long-range module or with further + message-passing blocks (``want_border``); the float64 cells of the frames, + a CPU tensor of shape ``(nf, 9)``, of a model with a long-range module; + and the border plan of a model with further message-passing blocks, a + send list of ``border_sizes[0]`` int32 entries and a swap table of + ``border_sizes[1]`` int32 rows on the CPU, which serve a node set without + halo nodes. """ from deepmd.dpmodel.utils.neighbor_graph import ( NeighborGraph, @@ -958,30 +970,51 @@ def build_synthetic_canonical_graph_inputs( compact.source_row_ptr, compact.source_order, ) - if spin is not None: - return (*compact_sample, spin) + trailing = [] if spin is None else [spin] if want_long_range: # Tracing reads the shape of the positions alone; distinct values keep - # the sample nodes apart. The communicator of a single domain is zero. - coord = 0.7 * torch.arange( - 3 * atype.shape[0], dtype=torch.float64, device=device - ).reshape(-1, 3) - communicator = torch.zeros(1, dtype=torch.int64, device="cpu") - box = torch.zeros(n_node.shape[0], 9, dtype=torch.float64, device="cpu") - return (*compact_sample, coord, communicator, box) - return compact_sample + # the sample nodes apart. + trailing.append( + 0.7 + * torch.arange( + 3 * atype.shape[0], dtype=torch.float64, device=device + ).reshape(-1, 3) + ) + if want_long_range or want_border: + # The communicator of a single domain is zero. + trailing.append(torch.zeros(1, dtype=torch.int64, device="cpu")) + if want_long_range: + trailing.append( + torch.zeros(n_node.shape[0], 9, dtype=torch.float64, device="cpu") + ) + if want_border: + # Swaps of no rows that receive past the last node leave every node + # owned. + send_count, swap_count = border_sizes + swaps = torch.zeros(swap_count, 5, dtype=torch.int32, device="cpu") + swaps[:, 4] = atype.shape[0] + trailing.append(torch.zeros(send_count, dtype=torch.int32, device=device)) + trailing.append(swaps) + return (*compact_sample, *trailing) def _build_canonical_graph_dynamic_shapes( - *sample_inputs: torch.Tensor, + *, + is_native_spin: bool = False, + long_range: bool = False, + border: bool = False, ) -> tuple: """Build dynamic node, edge and index-word axes for the compact ABI. - The trailing slots, the moments of a native-spin model or the positions, - the communicator and the cells of a model with a long-range module, are - present only for such models, so the sample length selects the shape - tuple. The communicator holds one address and is static; the cells follow - the frame axis. + The trailing slots follow the order of + :func:`build_synthetic_canonical_graph_inputs`: the moments of a + native-spin model, the positions of a model with a long-range module, the + communicator of such a model or of one with further message-passing + blocks, the cells of the former, and the border plan of the latter. The + communicator holds one address and is static; the positions and the + moments follow the node axis, the cells the frame axis, and the send list + and the swap table of the border plan have extents of their own, which may + be zero. """ nframes_dim = torch.export.Dim("nframes", min=1) node_dim = torch.export.Dim("n_node_total", min=1) @@ -1001,9 +1034,18 @@ def _build_canonical_graph_dynamic_shapes( {0: source_row_dim}, {0: source_order_dim}, ) - trailing = ({0: node_dim}, None, {0: nframes_dim})[ - : len(sample_inputs) - len(shapes) - ] + trailing = [] + if is_native_spin: + trailing.append({0: node_dim}) + if long_range: + trailing.append({0: node_dim}) + if long_range or border: + trailing.append(None) + if long_range: + trailing.append({0: nframes_dim}) + if border: + trailing.append({0: torch.export.Dim("n_halo_send", min=0)}) + trailing.append({0: torch.export.Dim("n_halo_swap", min=0)}) return (*shapes, *trailing) @@ -1480,7 +1522,7 @@ def _collect_metadata( } if is_spin: # The scheme is what selects the serving backend class in C++ - # (``deepmd_create_deepspin_backend_v2``): "native" is served by + # (``deepmd_create_deepspin_backend_v3``): "native" is served by # NativeSpinPTExpt, "deepspin" by DeepSpinPTExpt. It is a property of # the model alone, orthogonal to ``lower_input_kind`` below. meta["spin_scheme"] = spin_scheme @@ -1907,7 +1949,13 @@ def _select_graph_lower_kind(data: dict, *, allow_canonical: bool) -> str | None from deepmd.pt_expt.kernels.dpa4c.canonical import ( canonical_model_eligible as dpa4c_canonical_eligible, ) + from deepmd.pt_expt.kernels.dpa4c.canonical import ( + canonical_model_unsupported_reason as dpa4c_canonical_unsupported, + ) + reason = dpa4c_canonical_unsupported(model) + if reason is not None: + raise ValueError(reason) if dpa4c_canonical_eligible(model): return "dpa4c_canonical" if dpa1_canonical_eligible(model): @@ -1915,6 +1963,40 @@ def _select_graph_lower_kind(data: dict, *, allow_canonical: bool) -> str | None return "graph" +def compressed_export_unsupported_reason(model: torch.nn.Module) -> str | None: + """Return why the compressed export of a model would be refused on the target. + + The export folds the case embeddings of a compressed model and refuses + a DPA4C model of several blocks that the compact canonical operators of + the target do not serve (see + :func:`~deepmd.pt_expt.kernels.dpa4c.canonical.canonical_model_unsupported_reason`). + A freeze that compresses a model on its own initiative applies the same + judgment to the uncompressed model, on a copy with its case embeddings + folded, and keeps the uncompressed form where the judgment is a refusal. + + Parameters + ---------- + model + Uncompressed model to freeze. + + Returns + ------- + str or None + Diagnostic of the refusal, or ``None`` when the compressed archive + deploys on the target. + """ + from deepmd.pt_expt.kernels.dpa4c.canonical import ( + canonical_model_unsupported_reason, + ) + from deepmd.pt_expt.model.model import ( + BaseModel, + ) + + model = BaseModel.deserialize(model.serialize()) + _fold_case_embeddings(model) + return canonical_model_unsupported_reason(model, as_compressed=True) + + def _resolve_lower_kind(model_file: str, data: dict, lower_kind: str) -> str: """Resolve ``lower_kind="auto"`` to a concrete lower-forward schema. @@ -2249,6 +2331,11 @@ def _trace_and_export_impl( # Registry-dispatched (incl. native spin, type "native_spin"): the # pt_expt BaseModel registry returns this backend's torch class. model = BaseModel.deserialize(data["model"]) + if with_comm_dict and not _needs_with_comm_artifact(model, lower_kind): + raise ValueError( + f"with_comm_dict=True is unsupported for lower_kind={lower_kind!r}: " + "this model and lower do not use a separate with-comm artifact." + ) # The fold rebuilds the first fitting layers on the default device, where # the deserialized model resides, so it precedes the move below. _fold_case_embeddings(model) @@ -2436,20 +2523,47 @@ def _trace_and_export_impl( # the long range, and the communicator of the domains of a # decomposed frame. want_long_range = bool(model.atomic_model.required_topologies()) + # The compact lower of a model with further message-passing blocks + # reads the border plan of a decomposed frame, whose extents are + # kept distinct from the other axes. + want_border = bool(model.atomic_model.has_message_passing_across_ranks()) + border_sizes = ( + next_safe_prime( + e_sample + 3, + _forbidden | {nframes_sample, n_sample, n_sample + 1, e_sample}, + ), + next_safe_prime(3, _forbidden | {nframes_sample, nloc_sample}), + ) sample_inputs = build_synthetic_canonical_graph_inputs( model, e_sample, device=torch.device("cpu"), want_spin=is_native_spin, want_long_range=want_long_range, + want_border=want_border, + border_sizes=border_sizes, + ) + # The inputs after the graph, and the moment of a native-spin + # model, reach the lower by name, in the order of the samples. + graph_count = 9 if is_native_spin else 8 + names = ( + *(("coord",) if want_long_range else ()), + *(("communicator",) if want_long_range or want_border else ()), + *(("box",) if want_long_range else ()), + *(("halo_send", "halo_swaps") if want_border else ()), ) traced = model.forward_lower_canonical_graph_exportable( - *sample_inputs, + *sample_inputs[:graph_count], + **dict(zip(names, sample_inputs[graph_count:], strict=True)), do_atomic_virial=do_atomic_virial, tracing_mode="symbolic", _allow_non_fake_inputs=True, ) - dynamic_shapes = _build_canonical_graph_dynamic_shapes(*sample_inputs) + dynamic_shapes = _build_canonical_graph_dynamic_shapes( + is_native_spin=is_native_spin, + long_range=want_long_range, + border=want_border, + ) elif with_comm_dict: # Load libdeepmd_op_pt.so and register border_op fake/autograd # metadata now, mirroring the dense with-comm precedent below. @@ -2458,13 +2572,6 @@ def _trace_and_export_impl( ) ensure_comm_registered() - if not _needs_with_comm_artifact(model, lower_kind): - raise ValueError( - "with_comm_dict=True requested but the model's " - "descriptor does not need cross-rank message passing " - "(has_message_passing_across_ranks() is False) — " - "there's nothing to compile." - ) # The pt_expt Repformer with-comm override only supports nf=1 # (LAMMPS always drives multi-rank inference with one frame). # ``nloc_sample`` is the TOTAL flat node count carried by the @@ -2693,13 +2800,6 @@ def _trace_and_export_impl( ) ensure_comm_registered() - if not _needs_with_comm_artifact(model, lower_kind): - raise ValueError( - "with_comm_dict=True requested but the model's descriptor " - "does not need cross-rank message passing " - "(has_message_passing_across_ranks() is False) — " - "there's nothing to compile." - ) nloc_sample = nlist_t.shape[1] nall_sample = ext_atype.shape[1] nghost_sample = nall_sample - nloc_sample diff --git a/deepmd/utils/argcheck.py b/deepmd/utils/argcheck.py index 83b9f51f44..ed13571dc3 100644 --- a/deepmd/utils/argcheck.py +++ b/deepmd/utils/argcheck.py @@ -478,10 +478,16 @@ def descrpt_dpa4c_args() -> list[Argument]: return [ Argument( "rcut", - float, + [float, list[float]], optional=True, default=6.0, - doc="The outer cutoff radius.", + doc=( + "The cutoff radius shared by every message-passing block, or " + "a list of one non-increasing cutoff per block whose length " + "equals `n_blocks`. The first cutoff is the cutoff of the " + "neighbor graph and of the radial representation; the cutoff " + "of every further block bounds the edges its messages act on." + ), ), Argument( "channels", @@ -540,6 +546,22 @@ def descrpt_dpa4c_args() -> list[Argument]: "shape." ), ), + Argument( + "n_blocks", + int, + optional=True, + default=1, + doc=( + "Number of message-passing blocks. One block is the one-hop " + "descriptor. Every further block reads the features of the " + "edge sources in the previous block, widens the receptive " + "field by one cutoff and exchanges one node feature across " + "ranks. A model with several blocks extrapolates poorly in " + "pair contacts closer than about 0.45 of the covalent bond " + "length and should enable `bridging_method` wherever such " + "contacts can occur." + ), + ), Argument( "use_amp", bool, diff --git a/deepmd/utils/block_cutoff.py b/deepmd/utils/block_cutoff.py new file mode 100644 index 0000000000..9debe467d0 --- /dev/null +++ b/deepmd/utils/block_cutoff.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Per-block cutoff radii of message-passing descriptors.""" + +from __future__ import ( + annotations, +) + +from typing import ( + TYPE_CHECKING, +) + +import numpy as np + +if TYPE_CHECKING: + from collections.abc import ( + Sequence, + ) + + +def resolve_block_cutoffs(rcut: float | Sequence[float], n_blocks: int) -> list[float]: + """Return the cutoff radius of every message-passing block. + + A descriptor that stacks ``n_blocks`` message-passing blocks accepts one + cutoff for all of them or one cutoff per block. The neighbor graph is built + at the largest entry; whether the entries must be ordered is a property of + the descriptor that consumes them. + + Parameters + ---------- + rcut : float or Sequence[float] + A cutoff radius in Å shared by every block, or one radius per block. + n_blocks : int + Number of message-passing blocks. + + Returns + ------- + list[float] + Cutoff radius of every block in Å, with length ``n_blocks``. + + Raises + ------ + ValueError + If ``n_blocks`` is not a positive integer, if a sequence does not hold + exactly ``n_blocks`` entries, or if a cutoff is not positive. + """ + if isinstance(n_blocks, bool) or int(n_blocks) != n_blocks or n_blocks < 1: + raise ValueError(f"`n_blocks` must be a positive integer, got {n_blocks!r}") + n_blocks = int(n_blocks) + if np.isscalar(rcut): + cutoffs = [float(rcut)] * n_blocks + else: + cutoffs = [float(radius) for radius in rcut] + if len(cutoffs) != n_blocks: + raise ValueError( + f"`rcut` lists {len(cutoffs)} cutoff(s), but `n_blocks` is " + f"{n_blocks}; give one cutoff per block or a single cutoff for all" + ) + if not all(radius > 0.0 for radius in cutoffs): + raise ValueError(f"Every cutoff in `rcut` must be positive, got {rcut!r}") + return cutoffs diff --git a/deepmd/utils/json_schema.py b/deepmd/utils/json_schema.py index 6430bbff8a..c21c2bdd4c 100644 --- a/deepmd/utils/json_schema.py +++ b/deepmd/utils/json_schema.py @@ -18,7 +18,13 @@ def with_data_groups(schema: dict[str, Any], multi_task: bool) -> dict[str, Any] """Describe the same training-data fields for dictionaries and list items.""" training = schema["properties"]["training"] if multi_task: - training = training["properties"]["data_dict"]["additionalProperties"] + data_dict = training["properties"]["data_dict"] + # dargs describes the values of a repeated argument under ``items``, + # which JSON Schema applies to arrays only. The values of a repeated + # dictionary are constrained by ``additionalProperties``. + if "items" in data_dict: + data_dict["additionalProperties"] = data_dict.pop("items") + training = data_dict["additionalProperties"] data = training["properties"]["training_data"] data["items"] = { "type": "object", diff --git a/deepmd/utils/model_preset_data.py b/deepmd/utils/model_preset_data.py index e1274bb7f6..92d744bfb2 100644 --- a/deepmd/utils/model_preset_data.py +++ b/deepmd/utils/model_preset_data.py @@ -195,12 +195,32 @@ "fitting_net": {"neuron": [384, 384, 384]}, }, } +# A two-block grade ``-duo`` adds one message-passing block to its +# single-block grade. Nano has none, since the single-block Mini is more +# accurate at the same cost. +_DPA4C_DUO_BASES = ("mini", "neo", "air", "plus") +_DPA4C_GRADES.update( + { + f"{grade}-duo": { + **_DPA4C_GRADES[grade], + "descriptor": {**_DPA4C_GRADES[grade]["descriptor"], "n_blocks": 2}, + } + for grade in _DPA4C_DUO_BASES + } +) _DPA4C_VERSIONS: dict[str, dict[str, Any]] = { "v20260901": {"grades": ("nano", "mini", "neo", "air", "plus")}, # Fixed Gaussian centres in place of trainable Bessel frequencies. "v20260911": { "descriptor": {"basis_type": "gaussian/fix"}, - "grades": ("nano", "mini", "neo", "air", "plus"), + "grades": ( + "nano", + "mini", + "neo", + "air", + "plus", + *(f"{grade}-duo" for grade in _DPA4C_DUO_BASES), + ), }, } diff --git a/doc/install/install-lammps.md b/doc/install/install-lammps.md index 8b63b56b4f..eba8bc3afb 100644 --- a/doc/install/install-lammps.md +++ b/doc/install/install-lammps.md @@ -6,6 +6,12 @@ and DPA4C use `pair_style deepmd/kk`; compressed native-spin DPA4C models use There are two ways to install LAMMPS: the built-in mode and the plugin mode. The built-in mode builds LAMMPS along with the DeePMD-kit and DeePMD-kit will be loaded automatically when running LAMMPS. The plugin mode builds LAMMPS and a plugin separately, so one needs to use `plugin load` command to load the DeePMD-kit's LAMMPS plugin library. +For `dpa4spin/kk`, use LAMMPS 4 Jul 2026 or newer in place of the 2025 release +shown in the examples below. Configure both LAMMPS and the DeePMD-kit plugin +with `CMAKE_CXX_STANDARD=20`, and build the plugin against that same LAMMPS +source and Kokkos build. This requirement does not apply to the host +`dpa4spin` pair style. + ## Install LAMMPS's DeePMD-kit module (built-in mode) Before following this section, [DeePMD-kit C++ interface](install-from-source.md) should have be installed. @@ -156,12 +162,20 @@ The Open MPI package of conda-forge is built with CUDA support but disables it b conda create -n openmpi -c conda-forge openmpi ucx ``` -Configure LAMMPS and the DeePMD-kit C++ interface in new build directories with both compiler wrappers of that environment, `-D MPI_C_COMPILER=${mpi_root}/bin/mpicc -D MPI_CXX_COMPILER=${mpi_root}/bin/mpicxx`, where `${mpi_root}` is its prefix; CMake finds the MPI of each language separately. Launch a run on several GPUs with the `mpirun` of that installation, enabling its CUDA support for the launch: +Configure LAMMPS and the DeePMD-kit C++ interface in new build directories with both compiler wrappers of that environment, `-D MPI_C_COMPILER=${mpi_root}/bin/mpicc -D MPI_CXX_COMPILER=${mpi_root}/bin/mpicxx`, where `${mpi_root}` is its prefix; CMake finds the MPI of each language separately. Launch a run on several GPUs with the `mpirun` of that installation: + +```bash +mpirun --mca opal_cuda_support 1 --mca pml ucx -x UCX_MEMTYPE_CACHE=n -np 2 lmp -k on g 2 -sf kk -in in.lammps +``` + +The first option enables the CUDA support of Open MPI for the launch. The second selects UCX, which moves GPU buffers between the GPUs directly; Open MPI selects it by itself only on a node with an InfiniBand or RoCE adapter, and elsewhere, such as in a virtual machine without one, copies GPU buffers through host memory, which makes runs on several GPUs much slower. With `UCX_MEMTYPE_CACHE=n`, UCX queries the memory type of every buffer instead of taking it from a cache that can report a GPU buffer as host memory and make UCX abort. + +On a node with an InfiniBand or RoCE adapter, UCX may split every large message between two GPUs of the node across the direct GPU-to-GPU path and the adapter, whose share is far slower and holds up the whole message. Two more options keep each message on a single path, which the GPUs write directly: ```bash -mpirun --mca opal_cuda_support 1 -x UCX_MEMTYPE_CACHE=n -np 2 lmp -k on g 2 -sf kk -in in.lammps +mpirun --mca opal_cuda_support 1 --mca pml ucx -x UCX_MEMTYPE_CACHE=n -x UCX_MAX_RNDV_RAILS=1 -x UCX_RNDV_SCHEME=put_zcopy -np 4 lmp -k on g 4 -sf kk -in in.lammps ``` -With `UCX_MEMTYPE_CACHE=n`, UCX queries the memory type of every buffer instead of taking it from a cache that can report a GPU buffer as host memory and make UCX abort. +Models of several message-passing blocks exchange atom features at every block of every step and gain the most from them. -Launch a run on a single MPI rank without these options: it exchanges no atom data, and the CUDA support adds a memory-type query to every MPI call, which can lengthen the step of a small system by more than 10%. +Launch a run on a single MPI rank without these options: it exchanges no atom data, and the CUDA support of the MPI library slows the steps of a small system down noticeably. diff --git a/doc/model/dpa4c.md b/doc/model/dpa4c.md index dd8e2735d3..d62f79b1e4 100644 --- a/doc/model/dpa4c.md +++ b/doc/model/dpa4c.md @@ -5,9 +5,11 @@ DPA4C is the compact and compressible degree-wise descriptor of the DPA4 family. Where DPA4/SeZM targets the accuracy frontier through equivariant -message passing, DPA4C targets the throughput frontier: it reads each local -environment once, keeps no message-passing state, and admits a compressed CUDA -inference path in which its radial functions are replaced by tabulated splines. +message passing, DPA4C targets the throughput frontier: by default it reads +each local environment once, keeps no message-passing state, and compresses +into an archive that runs fast on GPUs and CPU hosts. A second +message-passing block makes the model more accurate at a higher cost (see +[Presets](#presets)). Choose DPA4C when the run is limited by simulation speed or system size rather than by the last increment of accuracy: large-scale molecular dynamics, long @@ -41,20 +43,23 @@ standard DeePMD energy model: For each atom the descriptor accumulates angular moments of its neighbors up to degree {ref}`lmax `, contracts them into rotationally invariant scalars, and passes only those scalars to the fitting -network. The neighbor shell is read exactly once: there is no message passing, -so an atom's descriptor depends only on the atoms within -{ref}`rcut ` of it. - -Three consequences shape how the model is used in practice. - -- **One-hop locality** keeps the per-step cost low and removes the cross-rank - halo exchange of intermediate features that a message-passing model needs, so - domain decomposition follows the ordinary pair-style path. -- **Exact smoothness at the cutoff.** The radial map is exactly zero at and - beyond `rcut`, with continuous derivatives, so the potential energy surface - stays smooth as neighbors cross the cutoff. -- **Analytic bounds on every per-atom quantity**, which is why compression needs - neither an extrapolation region nor overflow checking. +network. With one message-passing block, the default, an atom's descriptor +depends only on the atoms within +{ref}`rcut ` of it, which keeps the +cost of a step low. + +{ref}`n_blocks ` adds further +blocks. Each one reads the features that every neighbor computed in the +previous block, reweights the message that the neighbor sends, and adds the +directions of the neighbor's own environment to the moments of the atom, so +two atoms of the same element at the same distance no longer send the same +message. Every block extends the range of the descriptor by its cutoff. + +The radial functions vanish at `rcut` with continuous derivatives, and the +effect of every further block fades out at its own cutoff in the same way, so +the potential energy surface stays smooth as neighbors cross a cutoff. +[Architecture details](#architecture-details) describes the descriptor more +fully. ## Configuration @@ -86,22 +91,28 @@ documented default. } ``` -DPA4C has no `sel` option. It is graph-native: the descriptor consumes a -carry-all neighbor graph that holds every neighbor within `rcut`, rather than a -fixed-capacity neighbor list. There is no capacity to size, no dependence on the -densest frame in the dataset, and no truncation to guard against. +DPA4C has no `sel` option: it always uses every neighbor within `rcut`, so +there is no neighbor capacity to size and nothing is truncated. DPA4C defaults to `float32` -({ref}`precision `), which is also -what the compressed CUDA path requires. Double precision is neither necessary -nor supported for compressed inference. +({ref}`precision `), which +compression requires. Double precision is neither necessary nor supported for +compressed inference. ### Options that matter Every option, with its default and full description, is listed in the -{ref}`argument reference `. Four of them +{ref}`argument reference `. Five of them carry the accuracy–cost trade-off: +- **Depth** — {ref}`n_blocks `. + A second block makes the model more accurate than a single-block model one + or two sizes up, and costs several times as much per step once compressed + (see [Presets](#presets)); choose the depth with deployment in mind. `rcut` + then takes either one cutoff for every block or a list of non-increasing + cutoffs, one per block, such as `[6.0, 5.0]`. A further block evaluates only + the neighbors within its own cutoff, so a smaller cutoff makes it markedly + cheaper; the default of 6 Å for both blocks is the most accurate. - **Width** — {ref}`channels `, one of 8, 16, 32, 64, or 128. This is the primary scaling knob. It widens the scalar and edge features, the per-atom angular state, and the descriptor @@ -115,9 +126,9 @@ carry the accuracy–cost trade-off: {ref}`radial_modes `. Zero leaves every ordered atom-type pair with a rescaled copy of one shared radial function; larger values let each pair select its own radial shape from several - shared profiles. It spends per-edge work without enlarging the per-atom state, - which makes it the lever to reach for when memory rather than throughput is - the binding constraint. + shared profiles. It spends per-neighbor work without enlarging the per-atom + state, which makes it the lever to reach for when memory rather than + throughput is the binding constraint. - **Radial basis** — {ref}`basis_type ` and {ref}`n_radial ` select the @@ -127,27 +138,35 @@ carry the accuracy–cost trade-off: The fitting network is sized against the descriptor because the invariant output grows with `channels`. Unlike `radial_modes`, fitting width is not a free -trade against memory: it adds per-atom activations and the derivatives saved for -the force backward pass, so widening or deepening it costs throughput and -capacity together. Widen it only when validation error is limited by fitting +trade against memory: widening or deepening the network costs throughput and +memory together. Widen it only when validation error is limited by fitting capacity rather than by the descriptor. > [!IMPORTANT] -> The compressed CUDA path is compiled for `channels` in `{8, 16, 32, 64, 128}`, -> `lmax` in `{2, 3, 4}`, and `radial_modes` in `{0, 2, 4, 8}` only. A model -> trained outside those sets trains and evaluates correctly, but -> `dp --pt-expt compress` rejects it. Choose these values with deployment in -> mind. +> Compression supports `channels` in `{8, 16, 32, 64, 128}`, `lmax` in +> `{2, 3, 4}`, and `radial_modes` in `{0, 2, 4, 8}` only. Values of `channels` +> and `lmax` outside these sets are rejected at construction. Other non-negative +> integer values of `radial_modes` can train and evaluate, but cannot be +> compressed. Choose these values with deployment in mind. ### Presets -DPA4C preset names use `dpa4c--`. Available sizes are listed in -ascending computational cost; `neo` is the general-purpose starting point: +DPA4C preset names use `dpa4c--`. The single-block sizes are +listed in ascending computational cost, followed by the two-block sizes; `neo` +is the general-purpose starting point: + +| Version | Available sizes | +| ----------- | ---------------------------------------------------------------------------------- | +| `v20260911` | `nano`, `mini`, `neo`, `air`, `plus`, `mini-duo`, `neo-duo`, `air-duo`, `plus-duo` | +| `v20260901` | `nano`, `mini`, `neo`, `air`, `plus` | -| Version | Available sizes | -| ----------- | ------------------------------------ | -| `v20260911` | `nano`, `mini`, `neo`, `air`, `plus` | -| `v20260901` | `nano`, `mini`, `neo`, `air`, `plus` | +A `duo` size is the size of the same name with two message-passing blocks, for +example `dpa4c-air-duo-v20260911`. It is more accurate than the single-block +size one or two steps up. Uncompressed, it costs about twice as much per step +as its single-block size; compressed, roughly five to ten times as much on +large systems, because compression speeds up the second block far less than +the first. There is no `nano-duo`, because the single-block `mini` is more +accurate at the same cost. Setting `model.preset` supplies `type_map` (all 118 elements), `descriptor` and `fitting_net`. Run-specific settings are written alongside the preset: @@ -190,17 +209,16 @@ See [training energy models](train-energy.md) for the general workflow. ### Mixed precision -{ref}`use_amp ` runs the per-edge -stage under bfloat16 automatic mixed precision on CUDA during training. The -activation footprint of that stage scales with the edge count and dominates -memory, so enabling it lowers peak memory substantially; the destination -reduction and the invariant readout stay in the descriptor precision. Use it on -GPUs with native bf16 support. +{ref}`use_amp ` runs the +per-neighbor computations of the descriptor under bfloat16 automatic mixed +precision on CUDA during training, which lowers peak memory substantially; the +per-atom results stay in the descriptor precision. Use it on GPUs with native +bf16 support. -`use_amp` is an execution policy rather than model state: it is not serialized, -and evaluation and inference are governed independently by `DP_AMP_INFER`. A -model trained in full precision can therefore be evaluated under mixed -precision, and the reverse. +`use_amp` applies to training only and is not stored in the model; inference +has its own setting, `DP_AMP_INFER` (see +[Inference settings](#inference-settings)). A model trained in full precision +can therefore be evaluated under mixed precision, and the reverse. ## Zone bridging @@ -212,6 +230,10 @@ a physical repulsive wall instead of an extrapolated network output: E_i = E_i^{\mathrm{DPA4C}} + E_i^{\mathrm{pair}}. ``` +A model with several message-passing blocks needs it most: in contacts closer +than about 0.45 of the covalent bond length, which no training set samples, it +extrapolates worse than a single block. + Two potentials are available. `bridging_method: "zbl"` uses the Ziegler-Biersack-Littmark screened nuclear potential, which is derived from frozen atomic electron densities and covers every element. @@ -233,20 +255,14 @@ better trained model has not been established. > Pairs containing an element heavier than uranium, which the reference data does > not cover, fall back to ZBL. -The analytical term acts on every pair inside `rcut`. The learned model, in turn, is -made blind to pairs that are too close to be covered by training data. Below -the inner radius of the window a pair leaves the descriptor entirely: both -atoms are described exactly as if the other one were absent, and the pair -interacts through the analytical term alone. Between the inner and the outer -radius the pair enters the descriptor smoothly in two coupled ways: its -amplitude opens from zero to one, and the separation its radial functions -read is released at the same rate, from the midpoint of the window at the -inner radius to the true separation at the outer radius. A pair deep inside -the window therefore changes the descriptor through its amplitude alone, -with its radial features held where the retained training frames place them. -Beyond the outer radius the descriptor is the same as without bridging. The -transition keeps the energy three times continuously differentiable, like the -outer cutoff. +The analytical term acts on every pair inside `rcut`, and a window between an +inner and an outer radius hands each pair over between the two descriptions. +Below the inner radius a pair leaves the learned model entirely: both atoms are +described exactly as if the other one were absent, and the pair interacts +through the analytical term alone. Across the window the pair enters the +learned model smoothly, and beyond the outer radius the learned model is the +same as without bridging. The energy stays three times continuously +differentiable through the window, as it does at the outer cutoff. The two radii follow the size of the pair they apply to. Each is a fraction of the covalent bond length of that element pair, so a hydrogen pair is described @@ -275,45 +291,36 @@ Enable it on the model: ``` `type_map` must name chemical elements, because the analytical term is built -from their nuclear charges and the window from their covalent radii. `bridging_fraction_inner` and -`bridging_fraction_outer` adjust the two fractions. Giving `bridging_r_inner` -and `bridging_r_outer` instead replaces the rule with one window in Å applied -to every pair alike, which is worth doing only for a single-element system or -to reproduce an earlier model. See `examples/water/dpa4c/input-zbl.json` for a -complete input. - -Training frames that contain a pair closer than the midpoint of its window are -left out of the loss. Below the midpoint the learned contribution of the pair is -throttled to less than half of its amplitude, so a label there would ask the -model for a multiple of the energy it has to express; the separation the -radial functions read never falls below the midpoint either, and through the -lower half of the window it moves by less than 7 % of the window width, so the -radial features of a close pair stay next to the range the retained frames -cover. The threshold is derived from the window of each element pair, and +from their nuclear charges and the window from their covalent radii. +`bridging_fraction_inner` and `bridging_fraction_outer` adjust the two +fractions. Giving `bridging_r_inner` and `bridging_r_outer` instead replaces +the rule with one window in Å applied to every pair alike, which is worth doing +only for a single-element system or to reproduce an earlier model. See +`examples/water/dpa4c/input-zbl.json` for a complete input. + +Training leaves out frames that contain a pair closer than the midpoint of its +window, where the learned model has too little influence on the energy to fit a +label. The threshold follows from the window of each element pair, so `training_data.min_pair_dist` must stay unset on a bridged model. The data -statistics, including those of `dp change-bias`, are drawn under the same -filter, while validation batches are not filtered, so a validation error also -covers frames that training leaves out. +statistics, including those of `dp change-bias`, use the same filter, while +validation batches are not filtered, so a validation error also covers frames +that training leaves out. Bridging therefore relies on short-range training data. The labels that are kept have to reach into the window of every element pair, which in practice means adding dimer scans that run down to about half the covalent bond length. -Between the inner radius and the closest retained label the learned -contribution of the pair falls to zero with no data to shape it; labels inside -the window keep that descent smooth, while a pair whose window holds no label -can show spurious force maxima there. +Labels inside the window keep the hand-over smooth; a pair whose window holds +no label can show spurious force maxima there. The same model can be written explicitly as a `linear_ener` model over the DPA4C model and an `inner_potential` sub-model with `weights: "sum"`; the concise form above expands to it. -Bridging changes nothing in the workflow after training. The model freezes, -compresses and runs in LAMMPS like a plain DPA4C model: compression still -selects the compact canonical graph form, the fused kernels evaluate the -analytical term in the same pass over the neighbors as the descriptor, and multi-GPU runs -need no extra communication. Native spin and the frame charge state combine -with bridging; the analytical term depends on the separation alone and leaves -the magnetic force to the learned model. +Bridging changes nothing after training: a bridged model freezes, compresses +and runs in LAMMPS, on one GPU or several, like the plain DPA4C model of the +same depth. Native spin and the frame charge state combine with bridging; the +analytical term depends on the separation alone and leaves the magnetic force +to the learned model. A model trained without bridging fine-tunes into its bridged form, and the other way round. Add the bridging keys above to the input, keep the @@ -323,31 +330,24 @@ architecture, and start from the earlier checkpoint: dp --pt-expt train input-zbl.json --finetune model.ckpt.pt ``` -The descriptor and the fitting net are carried over although the bridged model -holds them one level deeper, inside the composition. Fine-tuning is required +The descriptor and the fitting network carry over. Fine-tuning is required rather than optional: the bridging window changes what the descriptor sees at short range, so the learned part is trained against the analytical term it is now summed with. ## Model compression -Compression is the deployment step. It replaces the analytic radial functions -and their type-pair modulation with tabulated splines evaluated by fused CPU or -CUDA kernels. Eligible CUDA models use the compact canonical graph form; -CPU models use the graph form with their dedicated kernels. Because the radial map is analytically bounded and -vanishes at `rcut`, the table needs no extrapolation region and no overflow -checking. - -Freeze and compress a checkpoint in one operation: +Compression is the deployment step: it tabulates the radial functions of the +model, which makes inference much faster on a GPU or a CPU host. Freeze and +compress a checkpoint in one operation: ```bash dp --pt-expt train input.json dp --pt-expt freeze -c model.ckpt.pt -o compressed_model --compress ``` -This writes `compressed_model.pt2` directly using the default compression -settings, without compiling an intermediate uncompressed archive. Compression -selects the export schema appropriate to the model and target device. +This writes `compressed_model.pt2` with the default compression settings. Set +the [inference settings](#inference-settings) before running it. A branch of a multi-task model is frozen by naming it with `--head`: @@ -355,25 +355,16 @@ A branch of a multi-task model is frozen by naming it with `--head`: dp --pt-expt freeze -c model.ckpt.pt -o compressed_branch --head CHOSEN_BRANCH --compress ``` -Where the branches share the fitting network, the case embedding that -distinguishes them is a constant of the branch, and the export folds it into -the bias of the first fitting layer, so the compressed branch takes the export -schema and the fused kernels of a single-task model. The fold is not possible -where the descriptor and the case embedding together are as wide as the first -fitting layer, or half as wide, because the residual connection of that layer -then carries the case embedding; such a branch keeps it and exports to the -graph form, which the export reports with a warning. - -On a CUDA device, compression also measures which kernel evaluates the fitting -network fastest on that GPU at each system size and stores the choices in the -archive. A kernel other than the default is chosen only where the measurement -finds it faster by more than 1% on a lightly loaded GPU and, under sustained -load, at most 1% slower both on a system of one element and on a system of up -to three elements. The measurement adds a few seconds to several minutes to a -compression, depending on the size of the model and on the GPU. All choices -give bit-identical results, so they affect only the speed. On a GPU of another -model, the archive uses the default choices instead; compress on the GPU model -that will run the simulations. +A branch whose fitting network is shared with the other branches compresses +like a single-task model, unless the widths of the descriptor and the case +embedding add up to the width of the first fitting layer or to half of it. +Such a branch is exported in a slower form, and the export reports it with a +warning. + +On a GPU, compression also tunes the archive for the GPU model it runs on, +which adds from a few seconds to several minutes. The tuning changes only the +speed, never the results. On a GPU of another model the archive runs with +untuned defaults, so compress on the GPU model that will run the simulations. To compress an existing frozen archive or choose the spline spacing, use the compression command: @@ -382,58 +373,74 @@ compression command: dp --pt-expt compress -i frozen_model.pt2 -o compressed_model.pt2 --step 0.01 ``` +`-s, --step` sets the uniform spline spacing in Å; a smaller value means a +finer table and a larger archive. DPA4C ignores `--extrapolate`, `--frequency` +and `--training-script`. + For ASE, `DP(model="model.pt", freeze=True)` automatically compresses supported DPA4C checkpoints and exports a single-process `.pt2`. If compression is not supported, ASE warns and retains the ordinary freeze path. See the [ASE interface](../third-party/ase.md). -Only `-s, --step` applies to DPA4C; it sets the uniform spline spacing in Å, and -a smaller value means a finer table and a larger model. The `--extrapolate`, -`--frequency`, and `--training-script` options exist for descriptors whose -tables need a second region, an overflow guard, or a minimum neighbor distance -computed from data; DPA4C needs none of them and ignores them. - Compression requires: - the PyTorch Exportable backend; - `precision: "float32"`; -- `channels`, `lmax` and `radial_modes` inside the compiled sets listed above; +- `channels`, `lmax` and `radial_modes` inside the supported sets listed under + [Options that matter](#options-that-matter); - an empty - {ref}`exclude_types `, since - the fused kernel has no type-exclusion branch. + {ref}`exclude_types `. `dp --pt-expt compress` and `freeze --compress` report an explicit error when -any of these is not met. -A model that excludes type pairs still trains and runs; deploy it as the -uncompressed graph archive. +any of these is not met. A model with excluded type pairs still trains and +runs; deploy it as an uncompressed archive. + +A model with several message-passing blocks compresses on the same terms and +runs compressed on one GPU or several, also with zone bridging, native spin or +a [latent-charge long-range module](long-range.md). For a GPU, its compressed +export additionally requires: + +- a fitting network with `float32` weights, `tanh` or `silu` hidden layers whose + widths are multiples of four, no `resnet_dt`, and no frame or atomic + parameters; +- no `pair_exclude_types` or `atom_exclude_types`; +- for a branch of a multi-task model, widths with which the branch compresses + like a single-task model, as described above; +- a long-range module, if any, that meets the conditions given in + [Long-range latent charges](long-range.md#training-and-inference), such as a + single charge channel. + +The compressed export of any other model with several blocks for a GPU reports +an error. On a CPU host, a model with several blocks runs through the slower +general path (see [CPU hosts](#cpu-hosts)). ## Running in LAMMPS -DPA4C uses the PyTorch `.pt2` (AOTInductor) export path and is served by the -`deepmd` pair style: +DPA4C runs in LAMMPS from its `.pt2` archive through the `deepmd` pair style: ```lammps pair_style deepmd compressed_model.pt2 pair_coeff * * O H ``` +A model with several message-passing blocks needs `atom_modify map yes` when it +runs on a single MPI rank. + ### Choosing a pair style -The compact canonical graph form exists so that the whole step can stay on the -device. Only the Kokkos pair styles use that device-resident entry point; the -host styles run the same archive through a per-step host round trip. On a GPU, -reaching DPA4C's advertised throughput therefore takes three things together: a -Kokkos-enabled LAMMPS build on the GPU backend, the compressed archive, and -`DP_CUDA_INFER` set at export time as described under -[Inference settings](#inference-settings). On a CPU host none of that applies -- -see [CPU hosts](#cpu-hosts). - -| Pair style | Build | Accepted archive | Execution | -| ------------- | ------------------------ | ------------------------- | ---------------------------------------------- | -| `deepmd` | any | graph lower or compressed | host round trip each step | -| `deepmd/kk` | Kokkos, GPU backend only | graph lower or compressed | device-resident; compressed uses fused kernels | -| `dpa4spin` | any, `atom_style spin` | graph lower or compressed | host round trip each step | -| `dpa4spin/kk` | Kokkos, GPU backend only | compressed only | device-resident | +On a GPU, the fastest runs take three things together: a LAMMPS build with the +KOKKOS package on its GPU backend, running the `/kk` pair styles; a compressed +archive; and `DP_CUDA_INFER` set when the archive is exported, as described +under [Inference settings](#inference-settings). The other pair styles run the +same archive more slowly, because they copy the data of every step through +host memory. For a host without a GPU, see [CPU hosts](#cpu-hosts). + +| Pair style | LAMMPS build | Archive | Use | +| ------------- | --------------------------------------- | -------------------------- | ------------------------------------------------- | +| `deepmd` | any | uncompressed or compressed | CPU hosts, and GPUs without KOKKOS | +| `deepmd/kk` | KOKKOS on a GPU | uncompressed or compressed | GPUs | +| `dpa4spin` | any, with `atom_style spin` | uncompressed or compressed | spin models on CPU hosts, and GPUs without KOKKOS | +| `dpa4spin/kk` | KOKKOS on a GPU, with `atom_style spin` | compressed | spin models on GPUs | Run under Kokkos with one GPU: @@ -441,22 +448,16 @@ Run under Kokkos with one GPU: lmp -k on g 1 -sf kk -in in.lammps ``` -On a single MPI rank, the Kokkos styles replay the evaluation of the model as -a CUDA graph from step to step. A step that also computes the per-atom virial, -which `compute centroid/stress/atom` requests (the Kokkos styles provide the -nine-component per-atom virial only), evaluates more outputs than the steps -around it: that step and the next one run without the replay, which resumes -one step later. Requesting the per-atom virial at a coarse interval keeps this -cost small. +Steps that compute the per-atom virial, which `compute centroid/stress/atom` +requests, are slower than the steps around them, so request it at a coarse +interval. The Kokkos pair styles provide the nine-component per-atom virial +only. ### CPU hosts -DPA4C has a second set of hand-written operators for the CPU, so a compressed -archive runs the same fused pipeline on a host without a GPU. They are selected -automatically -- there is no level to set, because they replace a lowering of -the same arithmetic and are faster wherever they apply -- and they carry the -same numerical contract as the CUDA ones: float32 model computation, no -reduced-precision path. +A compressed archive also runs fast on a host without a GPU. The CPU path is +selected automatically; there is no setting to choose it. Run with one thread +per physical core: ```bash export OMP_NUM_THREADS=$(nproc --all) @@ -465,20 +466,11 @@ export DP_INTER_OP_PARALLELISM_THREADS=1 lmp -in in.lammps ``` -Three conditions have to hold for the fused CPU path to be taken: - -- the archive is **compressed**, because the operator reads the radial table - rather than evaluating the radial network; -- `channels` is one of 8, 16, 32, 64, 128, `lmax` one of 2, 3, 4, `radial_modes` - one of 0, 2, 4, 8, the parameters are float32, and no type pairs are excluded; -- the descriptor is **not** spin-conditioned. The magnetic families need a - source-major counterpart of the destination scan, which only the CUDA kernels - carry; a spin model on a CPU host falls back to the portable path. - -`deepmd/kk` brings nothing on a CPU. Its purpose is to keep the neighbor list -device-resident and avoid host-device synchronization, which on a host is -already absent, and everything outside the pair style is about 2% of the step. -Use the plain `deepmd` style. +The fast CPU path serves compressed models with one message-passing block and +without native spin. A model with several blocks or with native spin runs on a +CPU host through the slower general path. Use `deepmd` for models without +native spin, or `dpa4spin` with `atom_style spin` for native-spin models. +The Kokkos pair styles bring no speedup on a CPU host. Two settings are worth knowing: @@ -493,68 +485,77 @@ Two settings are worth knowing: next to a high thread count. Launch LAMMPS directly, or reset the mask in the child. -Resident memory is roughly 16 to 31 KB per atom depending on the grade, so a 4 -GiB budget holds between 124 000 atoms (Plus) and 230 000 atoms (Nano). Most of -that is the neighbor graph, which depends on the cutoff rather than on the model -width. - -`DP_CPU_MALLOC_RETAIN` controls a heap policy that matters at these sizes. By -default the operator library keeps large blocks that a step reuses instead of -returning them to the kernel on every free; without it a molecular-dynamics step -re-faults its whole working set and loses more than half its throughput above -about 32 000 atoms. Retaining them costs a few hundred megabytes to a gigabyte -of resident memory. Set `DP_CPU_MALLOC_RETAIN=0` on a memory-constrained host to -trade that back. +A CPU run needs roughly 15 to 30 KB of memory per atom, most of it for the +neighbor list, which grows with `rcut` rather than with the size of the model. +By default the CPU path also keeps the memory that it reuses from step to step, +which makes large systems much faster and costs a few hundred megabytes to a +gigabyte; on a host short of memory, set `DP_CPU_MALLOC_RETAIN=0`. ### Multiple GPUs -Because DPA4C performs no message passing, it needs no cross-rank halo exchange -of intermediate features, and MPI domain decomposition follows the ordinary -pair-style path. Launch one MPI rank per GPU and make every target device -visible: +Run one MPI rank per GPU and make every GPU visible: ```bash -CUDA_VISIBLE_DEVICES=0,1,2,3 mpirun -np 4 lmp -in in.lammps +CUDA_VISIBLE_DEVICES=0,1,2,3 mpirun -np 4 lmp -k on g 4 -sf kk -in in.lammps ``` -Use a non-zero neighbor skin, for example `neighbor 2.0 bin`, to keep per-step -GPU memory stable; a zero skin rebuilds the neighbor list every step. - -Use an MPI library that can access GPU memory (CUDA-aware MPI); -[Install LAMMPS](../install/install-lammps.md#mpi-for-runs-on-several-gpus) -describes the setup. The KOKKOS package of LAMMPS then exchanges atom data -between ranks directly in GPU memory. When LAMMPS detects an MPI library without -this support, it prints a warning, turns GPU-aware communication off and copies -the whole position array through host memory at every step; -`pair_style deepmd/kk` and `pair_style dpa4spin/kk` then send the forces of -ghost atoms to the ranks that own them themselves, staging only those values in -host memory. On three RTX PRO 6000 GPUs with one million carbon atoms, a step of -the Nano model took 6.8 ms with a CUDA-aware Open MPI and 11.3 ms with an MPI -library without CUDA support, against 15.2 ms on one GPU. +Use an MPI library that can access GPU memory (CUDA-aware MPI), and launch it +with the options given in +[Install LAMMPS](../install/install-lammps.md#mpi-for-runs-on-several-gpus). +With an MPI library without that support, LAMMPS prints a warning and the run +proceeds, but noticeably more slowly. A model with several message-passing +blocks exchanges data between the GPUs at every step and depends most on these +options; it needs no other settings of its own. + +Use a non-zero neighbor skin, for example `neighbor 2.0 bin`, to keep the GPU +memory of every step stable; a zero skin rebuilds the neighbor list every step. + +For a model with several message-passing blocks, keep the default CUDA memory +allocator: under `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True`, Open MPI +over UCX aborts the run at its first step. ## Inference settings -Inference behavior is controlled by environment variables read when the model is -constructed: +Environment variables control inference: -| Environment variable | Default | Effect | -| ---------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `DP_CUDA_INFER` | `0` | Fused CUDA kernel level: `0` off, `1` fused descriptor and fitting, `2` additionally fuses force and virial assembly. Levels 1 and 2 are numerically identical. | -| `DP_AMP_INFER` | off | bf16 autocast over the per-edge stage during inference. Independent of the training-time `use_amp`. | -| `DP_TF32_INFER` | `0` | float32 matmul precision: `0` highest, `1` high, `2` medium. | -| `DP_CPU_MALLOC_RETAIN` | `1` | Whether the CPU operator library retains large heap blocks between steps. See [CPU hosts](#cpu-hosts). | +| Environment variable | Default | Effect | +| ---------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `DP_CUDA_INFER` | `0` | Fast GPU kernels: `0` off, `1` on, `2` on also for the forces and virials, the fastest level. Levels 1 and 2 give identical results. | +| `DP_AMP_INFER` | off | bfloat16 automatic mixed precision over the per-neighbor computations during inference. Independent of the training option `use_amp`. | +| `DP_TF32_INFER` | `0` | float32 matrix-multiplication precision: `0` highest, `1` high, `2` medium. | +| `DP_CPU_MALLOC_RETAIN` | `1` | Whether the CPU path keeps the memory it reuses from step to step. See [CPU hosts](#cpu-hosts). | -A compressed model needs `DP_CUDA_INFER` of at least `1` to reach its fused -path on a GPU; at `0` it evaluates through the portable path and the compression -brings no speedup. On a CPU host there is no equivalent level: the fused -operators are always selected when the model is eligible. For molecular dynamics sensitive to the smoothness of the potential -energy surface, keep `DP_TF32_INFER=0` and `DP_AMP_INFER=0`. +For eager inference, a compressed model runs fast on a GPU only with +`DP_CUDA_INFER` of at least `1`; at `0` compression brings no speedup there. +CUDA-host exports of DPA4C graph and compact canonical lowers select the +complete level-2 pipeline, including when `DP_CUDA_INFER` is `0` or `1`. +A CPU host needs no such setting. For molecular dynamics sensitive to the +smoothness of the potential energy surface, keep `DP_TF32_INFER=0` and +`DP_AMP_INFER=0`. > [!IMPORTANT] -> Set these variables **before** running `dp --pt-expt freeze` or -> `dp --pt-expt compress`. The exported `.pt2` is an AOTInductor artifact, so the -> kernel level and precision policy are captured into the graph at export time -> and are **not** re-evaluated when the `.pt2` is later loaded by LAMMPS. +> Set `DP_CUDA_INFER`, `DP_AMP_INFER` and `DP_TF32_INFER` **before** running +> `dp --pt-expt freeze` or `dp --pt-expt compress`. They are fixed into the +> `.pt2` archive when it is exported, with the DPA4C CUDA level-2 selection +> described above, and LAMMPS does **not** read them when it loads the archive. +> `DP_CPU_MALLOC_RETAIN` is read when the model runs. + +### Multi-block graph inputs + +The compact CUDA path for `n_blocks > 1` requires a globally bidirectional +neighbor graph: every edge has a reverse edge with the opposite displacement, +including periodic images. Python graph preparation checks this condition; +the single-domain C++ neighbor-list path checks it when the list is rebuilt. +A domain-decomposed list may be asymmetric locally because the reverse edge +belongs to another rank. Its producer must preserve the global condition. + +The zero-copy C GPU interface also relies on the producer to establish this +condition when building or updating its buffers. It does not copy or sort +those buffers on every evaluation. Concurrent distributed evaluations must +use distinct MPI communicators, with the threading support required by MPI. +Malformed device-resident halo indices or block cutoffs trigger asynchronous +CUDA assertions; these are not recoverable C API errors and may invalidate +the CUDA context. Validate distributed inputs before entering collective work. ## Native spin @@ -573,32 +574,18 @@ spin gradient of the same energy that yields the conservative force, The magnetic moment is an axial vector: it is even under spatial inversion and odd under time reversal, whereas a displacement is odd under inversion and even -under time reversal. The descriptor therefore emits only invariants of even -total spin order, which leaves it invariant under the full orthogonal group -acting jointly on positions and moments, including improper operations, and -invariant under time reversal. Reversing every moment leaves the energy -unchanged and reverses the magnetic force. - -Four families of spin channels are accumulated over the neighbor shell and -contracted against one another and against the geometric moments: - -| Family | Content | Interaction it represents | -| ----------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------------------------------- | -| Isotropic vector | $\sum_j \varphi_c(r_{ij})\,\hat{\mathbf{s}}_j$ | Heisenberg exchange | -| Bond-projected vector | $\sum_j \varphi_c(r_{ij})\,(\hat{\mathbf{s}}_j\cdot\hat{\mathbf{u}}_{ij})\,\hat{\mathbf{u}}_{ij}$ | Symmetric anisotropic exchange | -| Quadrupole | $\sum_j \varphi_c(r_{ij})\,B_2(\hat{\mathbf{s}}_j)$ | Biquadratic exchange, single-ion anisotropy | -| Magnitude and magnetic coordination | $\sum_j \varphi_c(r_{ij})\,\lvert\mathbf{s}_j\rvert^2$ and the gated neighbor count | Longitudinal and stoichiometric terms | - -Two-body Heisenberg exchange, biquadratic exchange and single-ion anisotropy -are represented exactly rather than approximately: each corresponds to a single -emitted invariant times a learned radial profile. The Dzyaloshinskii-Moriya -interaction is not representable at any order, because the invariant read-out -contains no antisymmetric contraction. - -The width of the spin block follows the degree-two width of the geometric -descriptor, so it is set by -{ref}`channels ` and has no knob of -its own. +under time reversal. The descriptor is invariant under rotations and +reflections acting jointly on positions and moments, and under time reversal: +reversing every moment leaves the energy unchanged and reverses the magnetic +force. + +It represents two-body Heisenberg exchange, biquadratic exchange and +single-ion anisotropy exactly, together with symmetric anisotropic exchange and +longitudinal terms in the magnitude of the moments. The +Dzyaloshinskii-Moriya interaction is not representable at any order. + +The spin part of the descriptor has no options of its own; its width follows +{ref}`channels `. ### Enabling native spin @@ -636,12 +623,11 @@ supported by this descriptor. Training uses the `ener_spin` loss, whose `start_pref_fm` and `limit_pref_fm` weight the magnetic force. A complete example is provided in `examples/spin/dpa4c/input.json`. -A moment is conditioned by a per-type gate and a reference magnitude measured -from the training corpus, so a non-magnetic type contributes exactly zero to -every spin channel and the magnitude of a magnetic type is normalized to order -unity. A model that declares a magnetic type but receives no moment is -rejected rather than evaluated at zero, since the latter is indistinguishable -from a broken data pipeline and reports a vanishing magnetic force. +A non-magnetic type contributes nothing to the spin part of the descriptor, +and the moments of each magnetic type are normalized by a reference magnitude +measured from the training data. A model with a magnetic type requires the +moments as input: evaluating it without them is an error, not an evaluation at +zero moments. ### Running a spin model in LAMMPS @@ -659,10 +645,11 @@ pair_style dpa4spin compressed_model.pt2 pair_coeff * * Ni O ``` -Ghost moments are supplied by the forward communication that `atom_style spin` -already performs, and the magnetic force is reduced back onto owning atoms -alongside the conservative force, so domain decomposition needs no additional -exchange. +The host pair style `dpa4spin` supports MPI domain decomposition. The GPU pair +style `dpa4spin/kk` requires LAMMPS 4 Jul 2026 or newer for correct spin-field +communication and host/device synchronization. Build the DeePMD-kit plugin +against the same LAMMPS and Kokkos build used to run it; see the +[Kokkos build instructions](../install/install-lammps.md#install-lammps-plugin-mode). By default the pair styles store the precession magnetic force that the LAMMPS SPIN package expects, the negative energy gradient `-dE/dS` scaled by the @@ -682,10 +669,6 @@ selects `-dE/dS` and requires `units metal`: pair_style dpa4spin/kk compressed_model.pt2 magnetic_force cartesian ``` -The pair styles declare the selected convention through the scalar integer -`Pair::extract("fm_cartesian_force", dim)`, zero for precession and one for -Cartesian, so such an integrator can reject a pair style left at the default. - A worked example, a rocksalt NiO cell in its type-II antiferromagnetic order, is provided in `examples/spin/dpa4c/lmp/`. @@ -708,32 +691,36 @@ The command reads the training checkpoint (`.pt`) or the frozen model (`.pt2`), compressed or not, and a ZBL-bridged model reports the embeddings of its learned model. Unlike a LAMMPS run, `dp embed` reads the [inference settings](#inference-settings) when it runs rather than at export: on -a GPU, a compressed model computes its descriptor with the fused kernels only -when `DP_CUDA_INFER` is at least `1` for the command. See +a GPU, a compressed model computes its descriptor fast only when +`DP_CUDA_INFER` is at least `1` for the command. See [model embeddings](../inference/embedding.md) for the output format and the Python interface. ## Data format -DPA4C consumes a mixed-type neighbor list, so it supports both the -[standard DeePMD-kit data format](../data/system.md) and the -[mixed-type data format](../data/system.md#mixed-type). Keep the `type_map` -order consistent across the dataset, the input file, and any downstream -`pair_coeff` mapping. +DPA4C supports both the [standard DeePMD-kit data format](../data/system.md) +and the [mixed-type data format](../data/system.md#mixed-type). Keep the +`type_map` order consistent across the dataset, the input file, and any +downstream `pair_coeff` mapping. ## Limitations - DPA4C is implemented for the PyTorch Exportable backend (`dp --pt-expt`). - Export uses `.pt2` (AOTInductor); the TorchScript freeze path is not used. -- Model compression requires `float32` and a configuration inside the compiled - sets listed under [Model compression](#model-compression). The resulting - archive runs fused kernels on either a CUDA device or a CPU host; only a - spin-conditioned model is CUDA-only. -- The device-resident inference path requires a Kokkos-enabled LAMMPS build on - the GPU backend. -- The descriptor is one-hop local by construction. Interactions beyond `rcut` - are not represented, and unlike a message-passing model the effective range - cannot be extended by adding layers. +- Model compression requires `float32` and supported values of `channels`, + `lmax` and `radial_modes` (see [Model compression](#model-compression)). A + compressed archive runs fast on a GPU or a CPU host; a spin model and a model + with several blocks run fast on GPUs only. +- The fastest GPU runs require a LAMMPS build with the KOKKOS package on its + GPU backend. +- A single-block descriptor is one-hop local: interactions beyond `rcut` are + not represented. Each further block extends the range by its own cutoff. +- A model with several blocks costs several times its single-block size per + step even when compressed, and on a GPU it compresses only under the + conditions given under [Model compression](#model-compression). In pair + contacts closer than about 0.45 of the covalent bond length, which no + training set samples, it extrapolates worse than a single block; enable + [zone bridging](#zone-bridging) wherever such contacts can occur. - Native spin requires the `native` scheme; the virtual-atom `deepspin` scheme is not supported. The Dzyaloshinskii-Moriya interaction is not representable, as explained under [Native spin](#native-spin). @@ -756,8 +743,8 @@ Each amplitude is multiplied by a smooth cutoff envelope whose value and first derivatives vanish at `rcut`, and by the real spherical harmonics of the neighbor direction up to degree `lmax`. -The per-atom state is the sum of these edge contributions, held separately for -each angular degree. Degree zero carries `channels` scalar values; higher +The per-atom state is the sum of these neighbor contributions, held separately +for each angular degree. Degree zero carries `channels` scalar values; higher degrees carry progressively fewer channels, each with `2l + 1` angular components. This tapering keeps the state small, which is what bounds both the per-step cost and the memory per atom. @@ -774,3 +761,17 @@ reach the fitting network: Because the contraction is exactly rotationally invariant, the descriptor and hence the energy are invariant under global rotation, and the forces obtained by differentiation are equivariant. + +A further block starts from the invariants and moments that every atom holds +after the previous block. Each neighbor turns them into a few saturated +features: equivariant keys, which describe how its own environment is oriented, +and an invariant state. For every neighbor pair an attention logit combines the +state of the neighbor, the orientation of its keys relative to the bond, and +the amplitude of the pair in one small hidden layer, so the effect of a +neighbor depends on its chemical environment and on the distance together. The +logit rescales the amplitude of the pair by a factor between zero and two, and +a softmax over the neighbors adds their keys to the moments of the atom. The +block then sums the neighbor contributions again and reads out the invariants +as before. Every map that produces the output of a block starts at zero, so a +model with several blocks starts out as its single-block counterpart, and every +block vanishes smoothly at its own cutoff. diff --git a/doc/model/long-range.md b/doc/model/long-range.md index 8797277cea..559f8060d0 100644 --- a/doc/model/long-range.md +++ b/doc/model/long-range.md @@ -234,21 +234,18 @@ charge state: the Python interface applies the state of each call, and LAMMPS the one given by the `charge_spin` keyword of `pair_style deepmd`. A compressed DPA4C model frozen for a CUDA device evaluates the long-range -term with a dedicated operator, which reads the positions of the atoms and -the cell. It enumerates the pairs of a non-periodic system itself, so that its -memory grows linearly with the number of atoms and its cost with their -square, and evaluates a periodic system on the mesh of its cell. The operator -serves the `les` kernel and the `sog` kernel of up to 32 Gaussians, with up to -8 charge channels, B-splines of order up to 12, a charge network without -frame or atomic parameters, and no `pair_exclude_types`. A model the -operator does not serve, like an uncompressed one, receives the pairs or the -mesh of each frame from the interface, so the memory of a non-periodic -evaluation grows with the square of the number of atoms. The operator -evaluates the long-range term together with the descriptor and both networks, -which is faster, when the module has one charge channel and a charge network -in `float32` with `tanh` or `silu` hidden layers whose widths are multiples of -four and without `resnet_dt`; the defaults give such a module in a compressed -model. +term on the GPU: a non-periodic system with memory that grows linearly with +the number of atoms and time that grows with their square, and a periodic +system on the mesh of its cell. This covers the `les` kernel and the `sog` +kernel of up to 32 Gaussians, with up to 8 charge channels, B-splines of order +up to 12, a charge network without frame or atomic parameters, and no +`pair_exclude_types`. Any other model, like an uncompressed one, evaluates a +non-periodic system with memory that grows with the square of the number of +atoms. A module with one charge channel and a charge network in `float32` with +`tanh` or `silu` hidden layers whose widths are multiples of four and without +`resnet_dt`, which the defaults give in a compressed model, runs faster still. +A compressed DPA4C model with several message-passing blocks requires such a +module on a CUDA device, on one MPI rank or on several. The following are not supported for a model with a long-range module: multi-rank (domain-decomposed) inference of a model that the dedicated diff --git a/doc/third-party/lammps-command.md b/doc/third-party/lammps-command.md index 5142a8e4ce..17f0e2feba 100644 --- a/doc/third-party/lammps-command.md +++ b/doc/third-party/lammps-command.md @@ -250,7 +250,7 @@ By default the pair style stores the precession magnetic force that the LAMMPS S ### Restrictions - The `dpa4spin` pair style requires `atom_style spin`, and on a single MPI rank an atom map (`atom_modify map yes`). -- `dpa4spin/kk` requires a compressed archive and a LAMMPS build with the KOKKOS package on the GPU backend. +- `dpa4spin/kk` requires a compressed archive and LAMMPS 4 Jul 2026 or newer with the KOKKOS package on the GPU backend. Earlier releases can corrupt ghost spin-field communication and migrated atom velocities. - In [plugin mode](../install/install-lammps.md#install-lammps-plugin-mode), `dpa4spin/kk` requires a DeePMD-kit plugin built with `DEEPMD_LAMMPS_KOKKOS=ON`. - The `fix nve/spin` of a stock LAMMPS build does not use the magnetic force of this pair style: the fix evaluates the magnetic force itself, through the pair styles whose names begin with `spin`. With no such pair style, the fix runs silently on a single MPI rank and stops with a sectoring error on several. Spin dynamics needs a LAMMPS build whose integrator reads the magnetic force of the pair style. - The `dpa4spin` pair style is provided in the USER-DEEPMD package, which is compiled from the DeePMD-kit, visit the [DeePMD-kit website](https://github.com/deepmodeling/deepmd-kit) for more information. diff --git a/skills/deepmd-install/SKILL.md b/skills/deepmd-install/SKILL.md index 6826b8f15c..4f47fdaa84 100644 --- a/skills/deepmd-install/SKILL.md +++ b/skills/deepmd-install/SKILL.md @@ -218,7 +218,8 @@ succeeds. Enable Kokkos only when the requested LAMMPS runtime requires it, and select the architecture supported by that exact LAMMPS/Kokkos source tree. For LAMMPS runs on several GPUs, build LAMMPS and the DeePMD-kit C/C++ interface against the same CUDA-aware MPI library, such as Open MPI with UCX, -and enable its CUDA support at run time as the matching LAMMPS page describes. +and enable its CUDA support and select UCX at run time as the matching LAMMPS +page describes. ## 4. Verify the requested interface diff --git a/skills/deepmd-train/models/dpa4c.md b/skills/deepmd-train/models/dpa4c.md index 8feaa071fc..12b45df27c 100644 --- a/skills/deepmd-train/models/dpa4c.md +++ b/skills/deepmd-train/models/dpa4c.md @@ -19,7 +19,12 @@ whereas DPA4C is implemented for `--pt-expt`. For a new DPA4C configuration, choose the family and grade first, then use a v20260911 preset. Available grades are nano, mini, neo, air, and plus; the name -format is dpa4c--v20260911. The maintained +format is dpa4c--v20260911. The presets dpa4c--duo-v20260911, +for mini, neo, air and plus, add a second message-passing block to the same +grade: more accurate than the single-block grade one or two steps up at a +similar uncompressed cost. Duo presets are compressible under the same +profile requirements, but their compressed steps cost more than those of the +single-block grades. The maintained examples/water/dpa4c/input.json uses dpa4c-nano-v20260911. The model section of a new energy input should contain the preset, the dataset's @@ -111,13 +116,17 @@ blindly replacing them with a newer preset. - `lmax` controls angular resolution. - `radial_modes` adds type-pair radial flexibility without widening the per-atom state. +- `n_blocks` sets the message-passing depth; `rcut` is then one cutoff for + every block or a non-increasing list of length `n_blocks`. A model with + several blocks needs `bridging_method` wherever pair contacts closer than + about 0.45 of the covalent bond length can occur. - `use_amp` is the descriptor's CUDA bf16 policy and is independent of `training.enable_compile` and `training.enable_tf32`. - DPA4C has no `sel`; it consumes a carry-all neighbor graph within `rcut`. Use a compression-supported configuration when compressed deployment is -required: `channels` in `{8, 16, 32, 64, 128}`, `lmax` in `{2, 3, 4}`, and -`radial_modes` in `{0, 2, 4, 8}`. +required: `channels` in `{8, 16, 32, 64, 128}`, `lmax` in +`{2, 3, 4}`, and `radial_modes` in `{0, 2, 4, 8}`. ## Freeze, compress, and test @@ -131,8 +140,9 @@ export DP_TF32_INFER=0 export DP_AMP_INFER=0 ``` -A compressed archive needs `DP_CUDA_INFER` of at least `1` to use the fused -path. Validate more aggressive precision settings against the target system. +CUDA-host exports of DPA4C graph and canonical lowers select level 2, including +when `DP_CUDA_INFER` is `0` or `1`. Validate more aggressive precision settings +against the target system. ```bash dp --pt-expt freeze -c model.ckpt.pt -o frozen_model --lower-kind graph diff --git a/source/api_c/include/c_api.h b/source/api_c/include/c_api.h index ff8903d341..b4b6d2d6fe 100644 --- a/source/api_c/include/c_api.h +++ b/source/api_c/include/c_api.h @@ -15,7 +15,7 @@ extern "C" { /** C API version. Bumped whenever the API is changed. * @since API version 22 */ -#define DP_C_API_VERSION 31 +#define DP_C_API_VERSION 32 /** * @brief Neighbor list. @@ -463,8 +463,26 @@ extern void DP_DeepPotComputeEdgesGPUFloat32(DP_DeepPot* dp, * requires the communicator, reads the positions of the nodes each rank owns, * and is evaluated on every rank at every step, a rank without nodes included * (``nall_nodes``, ``nloc`` and ``edge_storage`` zero), whose buffers sized by - * the nodes or by the edge storage may then be NULL. Every other model - * ignores it. + * the nodes or by the edge storage may then be NULL. A model with further + * message-passing blocks (DP_DeepPotCanonicalGraphRequiresHalo) exchanges the + * features of halo nodes through it with the ranks of ``halo``. Every other + * model ignores it. Overlapping distributed evaluations must use distinct + * communicators, duplicated collectively by the caller in the same order on + * every rank. Concurrent MPI calls require MPI_THREAD_MULTIPLE. Calls sharing + * a communicator must be serialized in the same order on all ranks. + * @param[in] halo The halo exchange of the node set, in host memory with its + * send list on the model device, or NULL for a node set without halo nodes. A + * model with further message-passing blocks reads features of the sources of + * its edges, so a node set with halo nodes requires it: the model refreshes + * the halo nodes from their owners before every block that reads them and + * evaluates the owned nodes alone, that is the energies of the owned nodes, + * the virial of the edges they own and the force of these edges on both of + * their nodes, so that the forces on the halo nodes are the contributions of + * this rank, which the caller folds onto their owners. Every rank of the + * decomposition then calls the model at every step, a rank without owned + * nodes included, and the messages travel on ``world``. Such a node set is + * evaluated without replay, and the host waits for the stream once before + * every swap with another rank. Every other model rejects a halo exchange. * @param[in] box The cell of a periodic system in host memory, nine values in * the length unit of the model, row-major with the lattice vectors as rows, * or NULL for a non-periodic system. A model with a long-range module that @@ -497,11 +515,49 @@ extern void DP_DeepPotComputeEdgesGPUFloat32(DP_DeepPot* dp, * and their captures, releases of graphs and charge-state updates, which wait * for the whole device, take turns; CUDA work outside DeePMD-kit that waits for * the whole device while a capture is under way invalidates it, and the model - * then evaluates without replay. + * then evaluates without replay. The communicator-isolation requirement above + * also applies to models evaluated by different threads. + * @note Multi-block DPA4C requires a globally bidirectional neighbor graph: + * every u-to-v edge has a v-to-u edge with the opposite displacement, + * including periodic images. A domain need store only its owned + * destination rows; reciprocal rows may belong to another rank. The + * caller establishes this invariant when building or updating the graph. + * This zero-copy entry point does not sort or copy graph data to verify + * it. * @note API versions 28 to 30 named this function * DP_DeepPotComputeCanonicalGraphGPU, without ``d_virial``, ``d_coord``, - * ``world``, ``box`` and ``stream``; a binary built against that name - * fails to load rather than call a function of another argument list. + * ``world``, ``halo``, ``box`` and ``stream``; a binary built against + * that name fails to load rather than call a function of another + * argument list. + * @since API version 32 + */ +extern void DP_DPA4ComputeCanonicalGraphGPU2( + DP_DeepPot* dp, + double* d_atom_energy, + double* d_force, + double* d_virial, + double* d_atom_virial, + const int64_t* d_atype, + const void* d_source, + DP_CanonicalIndexWidth index_width, + const float* d_edge_vec, + const int64_t* d_destination_row_ptr, + const int64_t* d_source_row_ptr, + const int64_t* d_source_order, + const double* d_coord, + void* world, + const DP_HaloExchange* halo, + const double* box, + int64_t nloc, + int64_t nall_nodes, + int64_t edge_storage, + void* stream); + +/** + * @brief API 31 canonical GPU evaluation without a halo exchange plan. + * + * The parameter order is preserved for existing binaries. A model that needs + * halo exchange requires DP_DPA4ComputeCanonicalGraphGPU2. * @since API version 31 */ extern void DP_DPA4ComputeCanonicalGraphGPU( @@ -550,13 +606,24 @@ extern bool DP_DeepPotUsesCanonicalGraphInference(DP_DeepPot* dp); */ extern bool DP_DeepPotCanonicalGraphRequiresSourceCSR(DP_DeepPot* dp); +/** + * @brief Query whether a compact canonical evaluation of a node set with halo + * nodes requires its halo exchange. + * + * A model with further message-passing blocks reads features of the sources + * of its edges, which DP_DPA4ComputeCanonicalGraphGPU2 refreshes on the halo + * nodes from their owners through the halo exchange of the node set. + * @since API version 31 + */ +extern bool DP_DeepPotCanonicalGraphRequiresHalo(DP_DeepPot* dp); + /** * @brief Query whether the model carries a long-range module. * * Such a module sums its interaction over every pair of atoms, and over the * images of the cell of a periodic system when it serves periodic systems, so * the model evaluates complete systems, and the device-resident entry - * DP_DPA4ComputeCanonicalGraphGPU passes it the node positions, the cell and, + * DP_DPA4ComputeCanonicalGraphGPU2 passes it the node positions, the cell and, * on several ranks, the communicator. * @since API version 31 */ @@ -1363,17 +1430,54 @@ extern void DP_DeepSpinComputeNListf3(DP_DeepSpin* dp, * @param[in] d_source_order Source-grouped int64 edge storage positions. * @param[in] d_spin FP32 per-node magnetic moment, shape ``(nall_nodes, 3)``; * halo rows carry their owner's moment. + * @param[in] world Pointer to the MPI communicator of the caller (an + * ``MPI_Comm``) when the system spans several ranks, or NULL on a single rank, + * under the contract described for DP_DPA4ComputeCanonicalGraphGPU2. + * @param[in] halo The halo exchange of the node set, or NULL for a node set + * without halo nodes, under the contract described for + * DP_DPA4ComputeCanonicalGraphGPU2; DP_DeepSpinCanonicalGraphRequiresHalo + * reports whether the model reads it. * @param[in] nloc Number of owned local nodes. * @param[in] nall_nodes Total local-plus-halo node count. * @param[in] edge_storage Number of edge storage slots. * @param[in] stream Accelerator stream (``cudaStream_t``) of the model device * on which the inputs were produced and the outputs will be consumed, under - * the contract described for DP_DPA4ComputeCanonicalGraphGPU. + * the contract described for DP_DPA4ComputeCanonicalGraphGPU2. * DP_DeepSpinSetChargeSpin waits for the work in flight on the model device * before it replaces the constants and for the replacement before it returns. * @note API version 30 named this function DP_DeepSpinComputeCanonicalGraphGPU, - * without ``d_virial`` and ``stream``; a binary built against that name - * fails to load rather than call a function of another argument list. + * without ``d_virial``, ``world``, ``halo`` and ``stream``; a binary + * built against that name fails to load rather than call a function of + * another argument list. + * @since API version 32 + */ +extern void DP_DPA4SpinComputeCanonicalGraphGPU2( + DP_DeepSpin* dp, + double* d_atom_energy, + double* d_force, + double* d_force_mag, + double* d_virial, + double* d_atom_virial, + const int64_t* d_atype, + const void* d_source, + DP_CanonicalIndexWidth index_width, + const float* d_edge_vec, + const int64_t* d_destination_row_ptr, + const int64_t* d_source_row_ptr, + const int64_t* d_source_order, + const float* d_spin, + void* world, + const DP_HaloExchange* halo, + int64_t nloc, + int64_t nall_nodes, + int64_t edge_storage, + void* stream); + +/** + * @brief API 31 canonical GPU evaluation without a halo exchange plan. + * + * The parameter order is preserved for existing binaries. A model that needs + * halo exchange requires DP_DPA4SpinComputeCanonicalGraphGPU2. * @since API version 31 */ extern void DP_DPA4SpinComputeCanonicalGraphGPU( @@ -1403,6 +1507,14 @@ extern void DP_DPA4SpinComputeCanonicalGraphGPU( */ extern bool DP_DeepSpinUsesCanonicalGraphInference(DP_DeepSpin* dp); +/** + * @brief Query whether a compact canonical evaluation of a node set with halo + * nodes requires its halo exchange for a DP spin model, as + * DP_DeepPotCanonicalGraphRequiresHalo does for a DP. + * @since API version 31 + */ +extern bool DP_DeepSpinCanonicalGraphRequiresHalo(DP_DeepSpin* dp); + /** * @brief Query whether a DP spin model is served under the native spin scheme * rather than the virtual-atom scheme. diff --git a/source/api_c/include/deepmd.hpp b/source/api_c/include/deepmd.hpp index 7fe1560b05..acfdf0f0eb 100644 --- a/source/api_c/include/deepmd.hpp +++ b/source/api_c/include/deepmd.hpp @@ -1365,10 +1365,12 @@ class DeepPot : public DeepBaseModel { * canonical_graph_requires_source_csr() holds. ``d_coord`` holds the node * positions, ``world`` the MPI communicator of a system on several ranks * and ``box`` the cell of a periodic system, which a model with a - * long-range module reads (has_long_range()); all three may be null for - * any other model. A non-null ``stream`` is the - * caller's accelerator stream on the model device. The arguments have the - * semantics of DP_DPA4ComputeCanonicalGraphGPU. + * long-range module reads (has_long_range()). ``halo`` is the halo exchange + * of a node set with halo nodes, which a model with further message-passing + * blocks reads (canonical_graph_requires_halo()) with ``world``. A null + * pointer omits any of them for a model that does not read it. A non-null + * ``stream`` is the caller's accelerator stream on the model device. The + * arguments have the semantics of DP_DPA4ComputeCanonicalGraphGPU2. */ void compute_canonical_graph_gpu(double* d_atom_energy, double* d_force, @@ -1383,16 +1385,17 @@ class DeepPot : public DeepBaseModel { const int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const int64_t nloc, const int64_t nall_nodes, const int64_t edge_storage, void* stream = nullptr) { - DP_DPA4ComputeCanonicalGraphGPU( + DP_DPA4ComputeCanonicalGraphGPU2( dp, d_atom_energy, d_force, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, d_source_row_ptr, - d_source_order, d_coord, world, box, nloc, nall_nodes, edge_storage, - stream); + d_source_order, d_coord, world, halo, box, nloc, nall_nodes, + edge_storage, stream); DP_CHECK_OK(DP_DeepPotCheckOK, dp); } @@ -1406,6 +1409,17 @@ class DeepPot : public DeepBaseModel { return result; } + /** + * @brief Query whether a compact canonical evaluation of a node set with + * halo nodes requires its halo exchange; see + * DP_DeepPotCanonicalGraphRequiresHalo. + */ + bool canonical_graph_requires_halo() const { + const bool result = DP_DeepPotCanonicalGraphRequiresHalo(dp); + DP_CHECK_OK(DP_DeepPotCheckOK, dp); + return result; + } + /** * @brief Query whether the model carries a long-range module, which * evaluates complete systems; see DP_DeepPotHasLongRange. @@ -1958,9 +1972,13 @@ class DeepSpin : public DeepBaseModel { * Graph, moment, and output pointers reside on the model device; the halo * rows of the moment carry their owner's value. ``d_virial`` may be null * when the virial is not requested. ``d_atom_virial`` may be null, and then - * so may the source CSR. A non-null ``stream`` is the caller's accelerator - * stream on the model device, with the semantics of - * DP_DPA4ComputeCanonicalGraphGPU. + * so may the source CSR. ``world`` and ``halo`` are the MPI communicator + * of a system on several ranks and the halo exchange of a node set with + * halo nodes, which a model with further message-passing blocks reads + * (canonical_graph_requires_halo()); a null pointer omits either for a + * model that does not read it. A non-null ``stream`` is the caller's + * accelerator stream on the model device, with the semantics of + * DP_DPA4ComputeCanonicalGraphGPU2. */ void compute_canonical_graph_gpu(double* d_atom_energy, double* d_force, @@ -1975,14 +1993,16 @@ class DeepSpin : public DeepBaseModel { const int64_t* d_source_row_ptr, const int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const int64_t nloc, const int64_t nall_nodes, const int64_t edge_storage, void* stream = nullptr) { - DP_DPA4SpinComputeCanonicalGraphGPU( + DP_DPA4SpinComputeCanonicalGraphGPU2( dp, d_atom_energy, d_force, d_force_mag, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, - d_source_row_ptr, d_source_order, d_spin, nloc, nall_nodes, + d_source_row_ptr, d_source_order, d_spin, world, halo, nloc, nall_nodes, edge_storage, stream); DP_CHECK_OK(DP_DeepSpinCheckOK, dp); } @@ -1996,6 +2016,17 @@ class DeepSpin : public DeepBaseModel { return result; } + /** + * @brief Query whether a compact canonical evaluation of a node set with + * halo nodes requires its halo exchange; see + * DP_DeepSpinCanonicalGraphRequiresHalo. + */ + bool canonical_graph_requires_halo() const { + const bool result = DP_DeepSpinCanonicalGraphRequiresHalo(dp); + DP_CHECK_OK(DP_DeepSpinCheckOK, dp); + return result; + } + /** * @brief Query whether the native spin scheme is active. */ diff --git a/source/api_c/src/c_api.cc b/source/api_c/src/c_api.cc index eeb196fead..4c5ada321a 100644 --- a/source/api_c/src/c_api.cc +++ b/source/api_c/src/c_api.cc @@ -1832,15 +1832,42 @@ void DP_DPA4ComputeCanonicalGraphGPU(DP_DeepPot* dp, const double* d_coord, void* world, const double* box, - const int64_t nloc, - const int64_t nall_nodes, - const int64_t edge_storage, + int64_t nloc, + int64_t nall_nodes, + int64_t edge_storage, void* stream) { + DP_DPA4ComputeCanonicalGraphGPU2( + dp, d_atom_energy, d_force, d_virial, d_atom_virial, d_atype, d_source, + index_width, d_edge_vec, d_destination_row_ptr, d_source_row_ptr, + d_source_order, d_coord, world, nullptr, box, nloc, nall_nodes, + edge_storage, stream); +} + +void DP_DPA4ComputeCanonicalGraphGPU2(DP_DeepPot* dp, + double* d_atom_energy, + double* d_force, + double* d_virial, + double* d_atom_virial, + const int64_t* d_atype, + const void* d_source, + DP_CanonicalIndexWidth index_width, + const float* d_edge_vec, + const int64_t* d_destination_row_ptr, + const int64_t* d_source_row_ptr, + const int64_t* d_source_order, + const double* d_coord, + void* world, + const DP_HaloExchange* halo, + const double* box, + const int64_t nloc, + const int64_t nall_nodes, + const int64_t edge_storage, + void* stream) { DP_REQUIRES_OK( dp, dp->dp.compute_canonical_graph_gpu( d_atom_energy, d_force, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, - d_source_row_ptr, d_source_order, d_coord, world, box, nloc, + d_source_row_ptr, d_source_order, d_coord, world, halo, box, nloc, nall_nodes, edge_storage, stream)); } @@ -1880,6 +1907,15 @@ bool DP_DeepPotCanonicalGraphRequiresSourceCSR(DP_DeepPot* dp) { } } +bool DP_DeepPotCanonicalGraphRequiresHalo(DP_DeepPot* dp) { + try { + return dp->dp.canonical_graph_requires_halo(); + } catch (deepmd::deepmd_exception& ex) { + dp->exception = std::string(ex.what()); + return false; + } +} + bool DP_DeepPotHasLongRange(DP_DeepPot* dp) { try { return dp->dp.has_long_range(); @@ -2245,16 +2281,43 @@ void DP_DPA4SpinComputeCanonicalGraphGPU(DP_DeepSpin* dp, const int64_t* d_source_row_ptr, const int64_t* d_source_order, const float* d_spin, - const int64_t nloc, - const int64_t nall_nodes, - const int64_t edge_storage, + int64_t nloc, + int64_t nall_nodes, + int64_t edge_storage, void* stream) { + DP_DPA4SpinComputeCanonicalGraphGPU2( + dp, d_atom_energy, d_force, d_force_mag, d_virial, d_atom_virial, d_atype, + d_source, index_width, d_edge_vec, d_destination_row_ptr, + d_source_row_ptr, d_source_order, d_spin, nullptr, nullptr, nloc, + nall_nodes, edge_storage, stream); +} + +void DP_DPA4SpinComputeCanonicalGraphGPU2(DP_DeepSpin* dp, + double* d_atom_energy, + double* d_force, + double* d_force_mag, + double* d_virial, + double* d_atom_virial, + const int64_t* d_atype, + const void* d_source, + DP_CanonicalIndexWidth index_width, + const float* d_edge_vec, + const int64_t* d_destination_row_ptr, + const int64_t* d_source_row_ptr, + const int64_t* d_source_order, + const float* d_spin, + void* world, + const DP_HaloExchange* halo, + const int64_t nloc, + const int64_t nall_nodes, + const int64_t edge_storage, + void* stream) { DP_REQUIRES_OK( dp, dp->dp.compute_canonical_graph_gpu( d_atom_energy, d_force, d_force_mag, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, - d_source_row_ptr, d_source_order, d_spin, nloc, nall_nodes, - edge_storage, stream)); + d_source_row_ptr, d_source_order, d_spin, world, halo, nloc, + nall_nodes, edge_storage, stream)); } bool DP_DeepSpinUsesCanonicalGraphInference(DP_DeepSpin* dp) { @@ -2266,6 +2329,15 @@ bool DP_DeepSpinUsesCanonicalGraphInference(DP_DeepSpin* dp) { } } +bool DP_DeepSpinCanonicalGraphRequiresHalo(DP_DeepSpin* dp) { + try { + return dp->dp.canonical_graph_requires_halo(); + } catch (deepmd::deepmd_exception& ex) { + dp->exception = std::string(ex.what()); + return false; + } +} + bool DP_DeepSpinUsesNativeSpinScheme(DP_DeepSpin* dp) { try { return dp->dp.uses_native_spin_scheme(); diff --git a/source/api_c/tests/test_deeppot_dpa4c_canonical_hpp.cc b/source/api_c/tests/test_deeppot_dpa4c_canonical_hpp.cc index c81003852e..f82e582bcf 100644 --- a/source/api_c/tests/test_deeppot_dpa4c_canonical_hpp.cc +++ b/source/api_c/tests/test_deeppot_dpa4c_canonical_hpp.cc @@ -21,5 +21,12 @@ INSTANTIATE_TYPED_TEST_SUITE_P(C, Models, CaseNames); +using HaloModels = ::testing::Types, + MultiblockSpin>; +INSTANTIATE_TYPED_TEST_SUITE_P(C, + TestInferDpa4cCanonicalHalo, + HaloModels, + CaseNames); + } // namespace dpa4c_canonical } // namespace deepmd_test diff --git a/source/api_cc/include/BackendPlugin.h b/source/api_cc/include/BackendPlugin.h index ef92c4a464..995a1d321b 100644 --- a/source/api_cc/include/BackendPlugin.h +++ b/source/api_cc/include/BackendPlugin.h @@ -23,13 +23,13 @@ class DipoleChargeModifierBase; * of another layout. **/ constexpr const char* DEEPMD_DEEPPOT_PLUGIN_CREATE_SYMBOL = - "deepmd_create_deeppot_backend_v2"; + "deepmd_create_deeppot_backend_v3"; constexpr const char* DEEPMD_DEEPPOT_PLUGIN_DELETE_SYMBOL = - "deepmd_delete_deeppot_backend_v2"; + "deepmd_delete_deeppot_backend_v3"; constexpr const char* DEEPMD_DEEPSPIN_PLUGIN_CREATE_SYMBOL = - "deepmd_create_deepspin_backend_v2"; + "deepmd_create_deepspin_backend_v3"; constexpr const char* DEEPMD_DEEPSPIN_PLUGIN_DELETE_SYMBOL = - "deepmd_delete_deepspin_backend_v2"; + "deepmd_delete_deepspin_backend_v3"; constexpr const char* DEEPMD_DEEPTENSOR_PLUGIN_CREATE_SYMBOL = "deepmd_create_deeptensor_backend_v1"; constexpr const char* DEEPMD_DEEPTENSOR_PLUGIN_DELETE_SYMBOL = diff --git a/source/api_cc/include/DeepPot.h b/source/api_cc/include/DeepPot.h index b1507d7103..1cfe95c808 100644 --- a/source/api_cc/include/DeepPot.h +++ b/source/api_cc/include/DeepPot.h @@ -436,6 +436,7 @@ class DeepPotBackend : public DeepBaseModelBackend { const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -445,6 +446,7 @@ class DeepPotBackend : public DeepBaseModelBackend { virtual bool uses_fp32_edge_vectors() const; virtual bool uses_canonical_graph_inference() const; virtual bool canonical_graph_requires_source_csr() const; + virtual bool canonical_graph_requires_halo() const; virtual bool has_long_range() const; }; @@ -912,6 +914,16 @@ class DeepPot : public DeepBaseModel { */ bool canonical_graph_requires_source_csr() const; + /** + * @brief Whether a compact canonical evaluation of a node set with halo + * nodes requires its halo exchange. + * + * A model with further message-passing blocks reads features of the sources + * of its edges, which compute_canonical_graph_gpu() refreshes on the halo + * nodes from their owners through the halo exchange of the node set. + */ + bool canonical_graph_requires_halo() const; + /** * @brief Whether the model carries a long-range module. * @@ -956,8 +968,24 @@ class DeepPot : public DeepBaseModel { * the communicator, reads the positions of the nodes each rank owns, and * is evaluated on every rank at every step, a rank without nodes included * (``nall_nodes``, ``nloc`` and ``edge_storage`` zero), whose buffers - * sized by the nodes or by the edge storage may then be null. Every other - * model ignores it. + * sized by the nodes or by the edge storage may then be null. A model with + * further message-passing blocks (canonical_graph_requires_halo()) + * exchanges the features of halo nodes through it with the ranks of + * ``halo``. Every other model ignores it. + * @param[in] halo The halo exchange of the node set, in host memory with + * its send list on the model device, or null for a node set without halo + * nodes. A model with further message-passing blocks reads features of the + * sources of its edges, so a node set with halo nodes requires it: the + * model refreshes the halo nodes from their owners before every block that + * reads them and evaluates the owned nodes alone, that is the energies of + * the owned nodes, the virial of the edges they own and the force of these + * edges on both of their nodes, so that the forces on the halo nodes are + * the contributions of this rank, which the caller folds onto their + * owners. Every rank of the decomposition then calls the model at every + * step, a rank without owned nodes included, and the messages travel on + * ``world``. Such a node set is evaluated without replay, and the host + * waits for the stream once before every swap with another rank. Every + * other model rejects a halo exchange. * @param[in] box The cell of a periodic system in host memory, nine values * in the length unit of the model, row-major with the lattice vectors as * rows, or null for a non-periodic system. A model with a long-range @@ -1006,6 +1034,7 @@ class DeepPot : public DeepBaseModel { const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, diff --git a/source/api_cc/include/DeepPotPTExpt.h b/source/api_cc/include/DeepPotPTExpt.h index bc17f23c01..a52188c30f 100644 --- a/source/api_cc/include/DeepPotPTExpt.h +++ b/source/api_cc/include/DeepPotPTExpt.h @@ -29,6 +29,7 @@ class TempFile; class ChargeStateFold; class GraphReplay; class PinnedCell; +struct HaloTensors; } // namespace deepmd::ptexpt namespace torch::inductor { @@ -393,6 +394,7 @@ class DeepPotPTExpt : public DeepPotBackend { const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -427,6 +429,7 @@ class DeepPotPTExpt : public DeepPotBackend { bool uses_fp32_edge_vectors() const override; bool uses_canonical_graph_inference() const override; bool canonical_graph_requires_source_csr() const override; + bool canonical_graph_requires_halo() const override; bool has_long_range() const override; private: @@ -458,6 +461,7 @@ class DeepPotPTExpt : public DeepPotBackend { const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -700,11 +704,15 @@ class DeepPotPTExpt : public DeepPotBackend { * model with a long-range module and ignored otherwise. * @param[in] world The MPI communicator (a pointer to an ``MPI_Comm``) of the * ranks a decomposed system spans, or NULL for a system that one rank holds - * whole; a model with a long-range module receives it after the positions. + * whole; a model with a long-range module receives it after the positions, + * and a model with further message-passing blocks before its halo exchange. * @param[in] cell The cell, a float64 CPU tensor of shape ``(1, 9)``: the * row-major cell of a periodic frame, or zero for a non-periodic one; a * model with a long-range module receives it after the communicator, and * every other model ignores it. + * @param[in] halo The halo exchange of the node set, which a model with + * further message-passing blocks receives after the communicator and every + * other model ignores. */ std::vector run_model_canonical_graph( const torch::Tensor& atype, @@ -717,7 +725,8 @@ class DeepPotPTExpt : public DeepPotBackend { const torch::Tensor& source_order, const torch::Tensor& coord, const void* world, - const torch::Tensor& cell); + const torch::Tensor& cell, + const ptexpt::HaloTensors& halo); /** * @brief Evaluate the long-range module on a rank that holds no node. diff --git a/source/api_cc/include/DeepSpin.h b/source/api_cc/include/DeepSpin.h index 338d76ff85..6cba7072f9 100644 --- a/source/api_cc/include/DeepSpin.h +++ b/source/api_cc/include/DeepSpin.h @@ -301,11 +301,14 @@ class DeepSpinBackend : public DeepBaseModelBackend { const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, void* stream); virtual bool uses_canonical_graph_inference() const; + virtual bool canonical_graph_requires_halo() const; /** * @brief Whether the backend serves the loaded artifact under the native @@ -617,6 +620,13 @@ class DeepSpin : public DeepBaseModel { */ bool uses_canonical_graph_inference() const; + /** + * @brief Whether a compact canonical evaluation of a node set with halo + * nodes requires its halo exchange, as DeepPot::canonical_graph_requires_halo + * reports for a model without spin. + */ + bool canonical_graph_requires_halo() const; + /** * @brief Whether the loaded artifact is served under the native spin * scheme rather than the virtual-atom scheme. @@ -652,6 +662,13 @@ class DeepSpin : public DeepBaseModel { * @param[in] d_source_order Source-grouped edge positions, [edge_storage]. * @param[in] d_spin Per-node magnetic moment, [nall_nodes * 3] row-major; *ghost rows carry their owner's moment. + * @param[in] world Pointer to the MPI communicator of the caller (an + *``MPI_Comm``) when the system spans several ranks, or null on a single + *rank, with the semantics of DeepPot::compute_canonical_graph_gpu. + * @param[in] halo The halo exchange of the node set, or null for a node set + *without halo nodes, with the semantics of + *DeepPot::compute_canonical_graph_gpu; canonical_graph_requires_halo() + *reports whether the model reads it. * @param[in] nloc Number of local atoms. * @param[in] nall_nodes Graph node count (local + ghost). * @param[in] edge_storage Allocated edge capacity. @@ -672,6 +689,8 @@ class DeepSpin : public DeepBaseModel { const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, diff --git a/source/api_cc/include/NativeSpinPTExpt.h b/source/api_cc/include/NativeSpinPTExpt.h index c7516ceab4..9a2fbf8522 100644 --- a/source/api_cc/include/NativeSpinPTExpt.h +++ b/source/api_cc/include/NativeSpinPTExpt.h @@ -23,6 +23,7 @@ namespace deepmd::ptexpt { class ChargeStateFold; class GraphReplay; +struct HaloTensors; } // namespace deepmd::ptexpt namespace torch::inductor { @@ -310,6 +311,10 @@ class NativeSpinPTExpt : public DeepSpinBackend { * [edge_storage]. * @param[in] d_spin Per-node magnetic moment, GPU [nall_nodes * 3] * row-major; ghost rows carry their owner's moment. + * @param[in] world Caller communicator; see + * DeepSpin::compute_canonical_graph_gpu. + * @param[in] halo Halo exchange of the node set; see + * DeepSpin::compute_canonical_graph_gpu. * @param[in] nloc Number of local atoms. * @param[in] nall_nodes Graph node count (local + ghost). * @param[in] edge_storage Allocated edge capacity. @@ -328,6 +333,8 @@ class NativeSpinPTExpt : public DeepSpinBackend { const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, @@ -335,6 +342,8 @@ class NativeSpinPTExpt : public DeepSpinBackend { bool uses_canonical_graph_inference() const override; + bool canonical_graph_requires_halo() const override; + bool uses_native_spin_scheme() const override; private: @@ -419,14 +428,17 @@ class NativeSpinPTExpt : public DeepSpinBackend { const bool atomic); /** - * @brief Run the nine-input compact canonical native-spin forward. + * @brief Run the compact canonical native-spin forward. * * Positional order: the eight dual-CSR graph tensors, then the per-node - * moment at index 8, which is the last slot -- the compact lower is traced - * without a conditional tail. + * moment at index 8, then, for a model with further message-passing + * blocks, the communicator ``world`` and the halo exchange of the node set. */ std::vector run_model_canonical( - const CanonicalGraphTensorPack& graph, const torch::Tensor& spin); + const CanonicalGraphTensorPack& graph, + const torch::Tensor& spin, + const void* world, + const ptexpt::HaloTensors& halo); /** * @brief Run the NeighborGraph native-spin forward. @@ -465,6 +477,11 @@ class NativeSpinPTExpt : public DeepSpinBackend { * the model carries a default or declares no width. * @param[in] aparam Atomic parameter, ``nloc * dim_aparam`` values, or empty * when the model declares no width. + * @param[in] world Communicator of the ranks a decomposed system spans, or + * null; the compact lower of a model with further message-passing blocks + * reads it with ``halo``. + * @param[in] halo Halo exchange of the node set for that lower, or null + * for a node set without halo nodes. */ std::map run_graph_payload( GraphTensorPack& graph, @@ -473,7 +490,9 @@ class NativeSpinPTExpt : public DeepSpinBackend { const torch::Tensor& spin, const std::vector& fparam, const std::vector& aparam, - const std::vector& charge_spin); + const std::vector& charge_spin, + const void* world = nullptr, + const ptexpt::HaloTensors* halo = nullptr); /** * @brief Bind the flat artifact outputs to their metadata key names. diff --git a/source/api_cc/include/canonical_graph.h b/source/api_cc/include/canonical_graph.h index 359569ec31..d9ba2d2745 100644 --- a/source/api_cc/include/canonical_graph.h +++ b/source/api_cc/include/canonical_graph.h @@ -9,6 +9,39 @@ typedef enum DP_CanonicalIndexWidth { DP_CANONICAL_INDEX64 = 8 } DP_CanonicalIndexWidth; +/** + * @brief Halo exchange of the node set of one domain of a decomposed system, + * the forward communication of a LAMMPS brick decomposition in model-node + * space. + * + * The node set holds the ``nloc`` owned nodes first, then the halo nodes, + * images of atoms that the swaps deliver. Swap ``s`` sends ``sendnum[s]`` + * nodes to rank ``sendproc[s]`` and receives ``recvnum[s]`` nodes from rank + * ``recvproc[s]`` into the consecutive halo nodes from ``firstrecv[s]``; the + * first swap receives into node ``nloc``, every further swap into the node + * after those of the swap before it, and together they fill every halo node. + * A swap whose two ranks are the caller's copies its nodes. The swaps run in + * order, so a swap may send halo nodes that an earlier swap received. The + * arrays of the swaps reside in host memory and the send list on the model + * device. + */ +typedef struct DP_HaloExchange { + /** Number of swaps. */ + int nswap; + /** Rank each swap sends to, shape ``(nswap)``. */ + const int* sendproc; + /** Rank each swap receives from, shape ``(nswap)``. */ + const int* recvproc; + /** Nodes each swap sends, shape ``(nswap)``. */ + const int* sendnum; + /** Nodes each swap receives, shape ``(nswap)``. */ + const int* recvnum; + /** First halo node each swap receives into, shape ``(nswap)``. */ + const int* firstrecv; + /** Nodes the swaps send, concatenated in swap order, on the device. */ + const int* d_sendlist; +} DP_HaloExchange; + #ifdef __cplusplus namespace deepmd { /** Select node-index width, preserving signed words at native host boundaries. diff --git a/source/api_cc/src/DeepPot.cc b/source/api_cc/src/DeepPot.cc index 68de144850..baaa291c68 100644 --- a/source/api_cc/src/DeepPot.cc +++ b/source/api_cc/src/DeepPot.cc @@ -670,6 +670,7 @@ void DeepPotBackend::compute_canonical_graph_gpu( const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -687,6 +688,7 @@ void DeepPotBackend::compute_canonical_graph_gpu( (void)d_source_order; (void)d_coord; (void)world; + (void)halo; (void)box; (void)nloc; (void)nall_nodes; @@ -703,6 +705,8 @@ bool DeepPotBackend::canonical_graph_requires_source_csr() const { return false; } +bool DeepPotBackend::canonical_graph_requires_halo() const { return false; } + bool DeepPotBackend::supports_device_edge_inference() const { return false; } bool DeepPotBackend::uses_canonical_graph_inference() const { return false; } @@ -776,6 +780,7 @@ void DeepPot::compute_canonical_graph_gpu( const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -784,7 +789,7 @@ void DeepPot::compute_canonical_graph_gpu( dp->compute_canonical_graph_gpu( d_atom_energy, d_force, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, d_source_row_ptr, - d_source_order, d_coord, world, box, nloc, nall_nodes, edge_storage, + d_source_order, d_coord, world, halo, box, nloc, nall_nodes, edge_storage, stream); } @@ -804,6 +809,10 @@ bool DeepPot::canonical_graph_requires_source_csr() const { return dp->canonical_graph_requires_source_csr(); } +bool DeepPot::canonical_graph_requires_halo() const { + return dp->canonical_graph_requires_halo(); +} + bool DeepPot::has_long_range() const { return dp->has_long_range(); } int DeepPot::dim_chg_spin() const { return dp->dim_chg_spin(); } diff --git a/source/api_cc/src/DeepPotJAXPlugin.cc b/source/api_cc/src/DeepPotJAXPlugin.cc index 2522148833..c2178479b5 100644 --- a/source/api_cc/src/DeepPotJAXPlugin.cc +++ b/source/api_cc/src/DeepPotJAXPlugin.cc @@ -4,7 +4,7 @@ #include "BackendPluginFactory.h" #include "DeepPotJAX.h" -extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, +extern "C" void* deepmd_create_deeppot_backend_v3(const char* model, int gpu_rank, const char* file_content, std::size_t file_content_size, @@ -13,7 +13,7 @@ extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deeppot_backend_v2(void* backend) { +extern "C" void deepmd_delete_deeppot_backend_v3(void* backend) { deepmd::plugin::delete_deeppot_backend(backend); } diff --git a/source/api_cc/src/DeepPotPDPlugin.cc b/source/api_cc/src/DeepPotPDPlugin.cc index 3bbd6842de..2ca283b0a5 100644 --- a/source/api_cc/src/DeepPotPDPlugin.cc +++ b/source/api_cc/src/DeepPotPDPlugin.cc @@ -4,7 +4,7 @@ #include "BackendPluginFactory.h" #include "DeepPotPD.h" -extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, +extern "C" void* deepmd_create_deeppot_backend_v3(const char* model, int gpu_rank, const char* file_content, std::size_t file_content_size, @@ -13,7 +13,7 @@ extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deeppot_backend_v2(void* backend) { +extern "C" void deepmd_delete_deeppot_backend_v3(void* backend) { deepmd::plugin::delete_deeppot_backend(backend); } diff --git a/source/api_cc/src/DeepPotPTExpt.cc b/source/api_cc/src/DeepPotPTExpt.cc index c92252c1e2..117560b8b3 100644 --- a/source/api_cc/src/DeepPotPTExpt.cc +++ b/source/api_cc/src/DeepPotPTExpt.cc @@ -663,7 +663,12 @@ std::vector DeepPotPTExpt::run_model_canonical_graph( const torch::Tensor& source_order, const torch::Tensor& coord, const void* world, - const torch::Tensor& cell) { + const torch::Tensor& cell, + const ptexpt::HaloTensors& halo) { + // The inputs that follow the graph come in the order of the compact lower: + // the positions, the communicator and the cell of a long-range module, and + // the communicator and the halo exchange of further message-passing blocks. + const bool reads_halo = canonical_graph_requires_halo(); std::vector inputs = { atype, n_node, n_local, canonicalIndexBytes(source), @@ -671,9 +676,17 @@ std::vector DeepPotPTExpt::run_model_canonical_graph( source_row_ptr, source_order}; if (long_range_) { inputs.push_back(coord); + } + if (long_range_ || reads_halo) { inputs.push_back(communicator_tensor(world)); + } + if (long_range_) { inputs.push_back(cell); } + if (reads_halo) { + inputs.push_back(halo.send_nodes); + inputs.push_back(halo.swaps); + } const std::lock_guard evaluation(evaluation_mutex_); return loader->run(inputs); } @@ -724,8 +737,8 @@ void DeepPotPTExpt::join_long_range_exchange(const void* world, torch::zeros({2}, i64.dtype(torch::kInt32)), torch::zeros({2, 3}, i64.dtype(torch::kFloat32)), torch::zeros({2}, i64), torch::zeros({2}, i64), torch::arange(2, i64), - torch::zeros({1, 3}, i64.dtype(torch::kFloat64)), world, - cell_tensor(box)); + torch::zeros({1, 3}, i64.dtype(torch::kFloat64)), world, cell_tensor(box), + ptexpt::empty_halo(device)); } std::vector DeepPotPTExpt::run_model_with_comm( @@ -1009,6 +1022,14 @@ void DeepPotPTExpt::compute(ENERGYVTYPE& ener, "long-range operator serves its long-range module; this archive uses " "another lower, so run it on a single rank."); } + if (canonical_graph_requires_halo() && multi_rank && + lmp_list.world == nullptr) { + throw deepmd::deepmd_exception( + "a model with further message-passing blocks exchanges the features " + "of ghost atoms between the ranks of a decomposed system through " + "their communicator, but the neighbor list carries none " + "(InputNlist::world)."); + } if (long_range_ && multi_rank && lmp_list.world == nullptr) { throw deepmd::deepmd_exception( "a model with a long-range module evaluates a system decomposed over " @@ -1153,6 +1174,10 @@ void DeepPotPTExpt::compute(ENERGYVTYPE& ener, nlist_data.jlist, mapping_, nloc, nall_real, /*node_count=*/multi_rank ? nall_real : nloc, /*row_centers=*/&nlist_data.ilist, fold_to_local); + if (lower_input_is_canonical_ && has_message_passing_ && !multi_rank) { + ptexpt::check_reciprocal_nlist(nlist_data.jlist, nlist_data.ilist, + mapping_, dcoord, nloc, nall_real); + } } else { nlist_data.padding(); firstneigh_tensor = createNlistTensor(nlist_data.jlist, nnei) @@ -1494,11 +1519,18 @@ void DeepPotPTExpt::compute(ENERGYVTYPE& ener, coord_Tensor.slice(1, 0, n_node_count).reshape({n_node_count, 3}); if (lower_input_is_canonical_) { const auto compact = compactCanonicalGraph(graph_pack); + // Further message-passing blocks refresh the features of the ghost + // nodes of an extended node set from their owners through the swaps + // of the neighbor list; a folded node set holds no ghost nodes. + const ptexpt::HaloTensors halo = + canonical_graph_requires_halo() && multi_rank + ? ptexpt::halo_tensors(lmp_list, fwd_map, nloc, device) + : ptexpt::empty_halo(device); flat_outputs = run_model_canonical_graph( compact.atype, compact.n_node, compact.n_local, compact.source, compact.edge_vec, compact.destination_row_ptr, compact.source_row_ptr, compact.source_order, node_coord, world, - long_range_ ? cell_tensor(long_range_box) : torch::Tensor()); + long_range_ ? cell_tensor(long_range_box) : torch::Tensor(), halo); } else { flat_outputs = run_model_graph( node_atype, n_node_tensor, n_local_tensor, graph_pack.edge_index, @@ -1887,7 +1919,8 @@ void DeepPotPTExpt::compute(ENERGYVTYPE& ener, compact.atype, compact.n_node, compact.n_local, compact.source, compact.edge_vec, compact.destination_row_ptr, compact.source_row_ptr, compact.source_order, node_coord, /*world=*/nullptr, - long_range_ ? cell_tensor(long_range_box) : torch::Tensor()); + long_range_ ? cell_tensor(long_range_box) : torch::Tensor(), + ptexpt::empty_halo(compact.atype.device())); } else { flat_outputs = run_model_graph( graph_tensors.atype, graph_tensors.n_node, graph_tensors.n_local, @@ -2790,6 +2823,7 @@ void DeepPotPTExpt::compute_canonical_graph_gpu_impl( const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -2799,6 +2833,23 @@ void DeepPotPTExpt::compute_canonical_graph_gpu_impl( throw deepmd::deepmd_exception( "compute_canonical_graph_gpu requires a compact canonical artifact."); } + // Further message-passing blocks read features of the sources of their + // edges, which the halo nodes of a node set receive from their owners + // through its halo exchange; every other model reads none. + const bool reads_halo = canonical_graph_requires_halo(); + if (halo != nullptr && !reads_halo) { + throw deepmd::deepmd_exception( + "compute_canonical_graph_gpu: a halo exchange was given, but the " + "model has no further message-passing blocks that read it."); + } + if (reads_halo && halo == nullptr && nall_nodes > nloc) { + throw deepmd::deepmd_exception( + "compute_canonical_graph_gpu: a model with further message-passing " + "blocks reads features of the halo nodes from their owners, so a node " + "set with " + + std::to_string(nall_nodes - nloc) + + " halo nodes requires its halo exchange."); + } if (!gpu_enabled) { throw deepmd::deepmd_exception( "compute_canonical_graph_gpu requires a CUDA device."); @@ -2938,10 +2989,14 @@ void DeepPotPTExpt::compute_canonical_graph_gpu_impl( {nall_nodes, 3}, opt_f64) : torch::Tensor(); std::map output; - extract_outputs(output, run_model_canonical_graph( - atype, n_node, n_local, source, edge_vec, - destination_row_ptr, source_row_ptr, - source_order, coord, world, cell)); + extract_outputs( + output, + run_model_canonical_graph( + atype, n_node, n_local, source, edge_vec, destination_row_ptr, + source_row_ptr, source_order, coord, world, cell, + halo != nullptr + ? ptexpt::halo_tensors(*halo, device, nloc, nall_nodes) + : ptexpt::empty_halo(device))); auto atom_energy = output["atom_energy"] .reshape({nall_nodes}) .slice(0, 0, nloc) @@ -2971,13 +3026,15 @@ void DeepPotPTExpt::compute_canonical_graph_gpu_impl( }; // A graph without halo nodes keeps its extents from step to step, so its // evaluation is replayed; a domain's halo changes its extent at every - // neighbor rebuild, so a graph with halo nodes is evaluated eagerly. A - // model with a long-range module reads the node positions, whose address - // is then part of the key, and is evaluated eagerly over several ranks, + // neighbor rebuild, so a graph with halo nodes is evaluated eagerly, as + // is one whose halo exchange communicates between the kernels. A model + // with a long-range module reads the node positions, whose address is + // then part of the key, and is evaluated eagerly over several ranks, // where it may communicate between its kernels. A replay reads the cell // of its call, while the mesh size of the cell fixes the buffers and the // launches of the evaluation, so the size joins the key. - bool replay = nloc == nall_nodes && !(long_range && world != nullptr); + bool replay = nloc == nall_nodes && halo == nullptr && + !(long_range && world != nullptr); std::array mesh = {}; if (long_range) { if (!long_range_box.empty()) { @@ -3101,6 +3158,7 @@ void DeepPotPTExpt::compute_canonical_graph_gpu( const std::int64_t* d_source_order, const double* d_coord, void* world, + const DP_HaloExchange* halo, const double* box, const std::int64_t nloc, const std::int64_t nall_nodes, @@ -3109,7 +3167,7 @@ void DeepPotPTExpt::compute_canonical_graph_gpu( compute_canonical_graph_gpu_impl( d_atom_energy, d_force, d_virial, d_atom_virial, d_atype, d_source, index_width, d_edge_vec, d_destination_row_ptr, d_source_row_ptr, - d_source_order, d_coord, world, box, nloc, nall_nodes, edge_storage, + d_source_order, d_coord, world, halo, box, nloc, nall_nodes, edge_storage, stream); } @@ -3131,6 +3189,10 @@ bool DeepPotPTExpt::canonical_graph_requires_source_csr() const { return canonical_requires_source_csr_; } +bool DeepPotPTExpt::canonical_graph_requires_halo() const { + return lower_input_is_canonical_ && has_message_passing_; +} + bool DeepPotPTExpt::has_long_range() const { return long_range_; } #endif diff --git a/source/api_cc/src/DeepPotPTExptPlugin.cc b/source/api_cc/src/DeepPotPTExptPlugin.cc index da6b6f93b0..0e1052eea1 100644 --- a/source/api_cc/src/DeepPotPTExptPlugin.cc +++ b/source/api_cc/src/DeepPotPTExptPlugin.cc @@ -57,7 +57,7 @@ bool native_spin_backend_serves(const char* model) { } // namespace #endif -extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, +extern "C" void* deepmd_create_deeppot_backend_v3(const char* model, int gpu_rank, const char* file_content, std::size_t file_content_size, @@ -74,11 +74,11 @@ extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, #endif } -extern "C" void deepmd_delete_deeppot_backend_v2(void* backend) { +extern "C" void deepmd_delete_deeppot_backend_v3(void* backend) { deepmd::plugin::delete_deeppot_backend(backend); } -extern "C" void* deepmd_create_deepspin_backend_v2( +extern "C" void* deepmd_create_deepspin_backend_v3( const char* model, int gpu_rank, const char* file_content, @@ -102,7 +102,7 @@ extern "C" void* deepmd_create_deepspin_backend_v2( #endif } -extern "C" void deepmd_delete_deepspin_backend_v2(void* backend) { +extern "C" void deepmd_delete_deepspin_backend_v3(void* backend) { deepmd::plugin::delete_deepspin_backend(backend); } diff --git a/source/api_cc/src/DeepPotPTPlugin.cc b/source/api_cc/src/DeepPotPTPlugin.cc index f024c4e10a..3fc94a456e 100644 --- a/source/api_cc/src/DeepPotPTPlugin.cc +++ b/source/api_cc/src/DeepPotPTPlugin.cc @@ -6,7 +6,7 @@ #include "DeepSpinPT.h" #include "DeepTensorPT.h" -extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, +extern "C" void* deepmd_create_deeppot_backend_v3(const char* model, int gpu_rank, const char* file_content, std::size_t file_content_size, @@ -15,11 +15,11 @@ extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deeppot_backend_v2(void* backend) { +extern "C" void deepmd_delete_deeppot_backend_v3(void* backend) { deepmd::plugin::delete_deeppot_backend(backend); } -extern "C" void* deepmd_create_deepspin_backend_v2( +extern "C" void* deepmd_create_deepspin_backend_v3( const char* model, int gpu_rank, const char* file_content, @@ -29,7 +29,7 @@ extern "C" void* deepmd_create_deepspin_backend_v2( model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deepspin_backend_v2(void* backend) { +extern "C" void deepmd_delete_deepspin_backend_v3(void* backend) { deepmd::plugin::delete_deepspin_backend(backend); } diff --git a/source/api_cc/src/DeepPotTFPlugin.cc b/source/api_cc/src/DeepPotTFPlugin.cc index f1daf082a9..7dd623c231 100644 --- a/source/api_cc/src/DeepPotTFPlugin.cc +++ b/source/api_cc/src/DeepPotTFPlugin.cc @@ -46,7 +46,7 @@ void convert_pbtxt_to_pb_impl(const char* pbtxt, const char* pb) { } // namespace -extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, +extern "C" void* deepmd_create_deeppot_backend_v3(const char* model, int gpu_rank, const char* file_content, std::size_t file_content_size, @@ -55,11 +55,11 @@ extern "C" void* deepmd_create_deeppot_backend_v2(const char* model, model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deeppot_backend_v2(void* backend) { +extern "C" void deepmd_delete_deeppot_backend_v3(void* backend) { deepmd::plugin::delete_deeppot_backend(backend); } -extern "C" void* deepmd_create_deepspin_backend_v2( +extern "C" void* deepmd_create_deepspin_backend_v3( const char* model, int gpu_rank, const char* file_content, @@ -69,7 +69,7 @@ extern "C" void* deepmd_create_deepspin_backend_v2( model, gpu_rank, file_content, file_content_size, error_message); } -extern "C" void deepmd_delete_deepspin_backend_v2(void* backend) { +extern "C" void deepmd_delete_deepspin_backend_v3(void* backend) { deepmd::plugin::delete_deepspin_backend(backend); } diff --git a/source/api_cc/src/DeepSpin.cc b/source/api_cc/src/DeepSpin.cc index 83aa44c08b..3a9efc46b9 100644 --- a/source/api_cc/src/DeepSpin.cc +++ b/source/api_cc/src/DeepSpin.cc @@ -483,6 +483,8 @@ void DeepSpinBackend::compute_canonical_graph_gpu( const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, @@ -499,6 +501,8 @@ void DeepSpinBackend::compute_canonical_graph_gpu( (void)d_source_row_ptr; (void)d_source_order; (void)d_spin; + (void)world; + (void)halo; (void)nloc; (void)nall_nodes; (void)edge_storage; @@ -510,6 +514,8 @@ void DeepSpinBackend::compute_canonical_graph_gpu( bool DeepSpinBackend::uses_canonical_graph_inference() const { return false; } +bool DeepSpinBackend::canonical_graph_requires_halo() const { return false; } + bool DeepSpinBackend::uses_native_spin_scheme() const { return false; } void DeepSpin::compute_canonical_graph_gpu( @@ -526,6 +532,8 @@ void DeepSpin::compute_canonical_graph_gpu( const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, @@ -534,17 +542,21 @@ void DeepSpin::compute_canonical_graph_gpu( // canonical inference override the hook, while the others inherit the // throwing default. ``libdeepmd_cc`` does not link any backend, so the // dispatch stays virtual rather than casting to a concrete backend type. - dp->compute_canonical_graph_gpu(d_atom_energy, d_force, d_force_mag, d_virial, - d_atom_virial, d_atype, d_source, index_width, - d_edge_vec, d_destination_row_ptr, - d_source_row_ptr, d_source_order, d_spin, - nloc, nall_nodes, edge_storage, stream); + dp->compute_canonical_graph_gpu( + d_atom_energy, d_force, d_force_mag, d_virial, d_atom_virial, d_atype, + d_source, index_width, d_edge_vec, d_destination_row_ptr, + d_source_row_ptr, d_source_order, d_spin, world, halo, nloc, nall_nodes, + edge_storage, stream); } bool DeepSpin::uses_canonical_graph_inference() const { return dp->uses_canonical_graph_inference(); } +bool DeepSpin::canonical_graph_requires_halo() const { + return dp->canonical_graph_requires_halo(); +} + bool DeepSpin::uses_native_spin_scheme() const { return dp->uses_native_spin_scheme(); } diff --git a/source/api_cc/src/NativeSpinPTExpt.cc b/source/api_cc/src/NativeSpinPTExpt.cc index 14ba150421..32f8c2e3f9 100644 --- a/source/api_cc/src/NativeSpinPTExpt.cc +++ b/source/api_cc/src/NativeSpinPTExpt.cc @@ -582,14 +582,30 @@ void NativeSpinPTExpt::get_type_map(std::string& type_map_str) { } std::vector NativeSpinPTExpt::run_model_canonical( - const CanonicalGraphTensorPack& graph, const torch::Tensor& spin) { + const CanonicalGraphTensorPack& graph, + const torch::Tensor& spin, + const void* world, + const ptexpt::HaloTensors& halo) { // The moment shares the float32 precision of the compact geometry; the cast // is a no-op for a caller that already holds a float32 tensor. + std::vector inputs = {graph.atype, + graph.n_node, + graph.n_local, + canonicalIndexBytes(graph.source), + graph.edge_vec, + graph.destination_row_ptr, + graph.source_row_ptr, + graph.source_order, + spin.to(torch::kFloat32)}; + if (canonical_graph_requires_halo()) { + inputs.push_back(torch::full( + {1}, static_cast(reinterpret_cast(world)), + torch::TensorOptions().dtype(torch::kInt64))); + inputs.push_back(halo.send_nodes); + inputs.push_back(halo.swaps); + } const std::lock_guard evaluation(evaluation_mutex_); - return loader->run({graph.atype, graph.n_node, graph.n_local, - canonicalIndexBytes(graph.source), graph.edge_vec, - graph.destination_row_ptr, graph.source_row_ptr, - graph.source_order, spin.to(torch::kFloat32)}); + return loader->run(inputs); } std::vector NativeSpinPTExpt::run_model_graph( @@ -632,15 +648,21 @@ std::map NativeSpinPTExpt::run_graph_payload( const torch::Tensor& spin, const std::vector& fparam, const std::vector& aparam, - const std::vector& charge_spin) { + const std::vector& charge_spin, + const void* world, + const ptexpt::HaloTensors* halo) { graph.edge_mask = deepmd::applyPairExclusion(graph.edge_index, graph.edge_mask, graph.atype, pair_exclude_table_, ntypes); canonicalizeGraphPayload(graph, node_count); std::map output_map; if (canonical_abi_) { - extract_outputs(output_map, - run_model_canonical(compactCanonicalGraph(graph), spin)); + extract_outputs( + output_map, + run_model_canonical(compactCanonicalGraph(graph), spin, world, + halo != nullptr + ? *halo + : ptexpt::empty_halo(graph.atype.device()))); // The compact lower reports the per-atom virial with the fitting axis // still in place; the graph lower already drops it. deepmd::flatten_canonical_atom_virial(output_map); @@ -738,12 +760,20 @@ void NativeSpinPTExpt::compute(ENERGYVTYPE& ener, // backend factory normally keeps such an archive with ``DeepSpinPTExpt``, // which owns the with-comm route, so this guard stands for a caller that // constructs this class directly. - if (multi_rank && has_message_passing_) { + if (multi_rank && has_message_passing_ && !canonical_abi_) { throw deepmd::deepmd_exception( "this native-spin artifact reads intermediate features of " "neighbouring nodes, which domain decomposition cannot supply for a " "ghost node; run it on a single MPI rank."); } + if (multi_rank && canonical_graph_requires_halo() && + lmp_list.world == nullptr) { + throw deepmd::deepmd_exception( + "a model with further message-passing blocks exchanges the features " + "of ghost atoms between the ranks of a decomposed system through " + "their communicator, but the neighbor list carries none " + "(InputNlist::world)."); + } if (nall_real == 0) { // A rank holding neither a real local atom nor a real ghost contributes @@ -809,6 +839,10 @@ void NativeSpinPTExpt::compute(ENERGYVTYPE& ener, /*fold_to_local=*/!multi_rank); edge_index_tensor = topology.edge_index; edge_index_ext_tensor = topology.edge_index_ext; + if (canonical_graph_requires_halo() && !multi_rank) { + ptexpt::check_reciprocal_nlist(nlist_data.jlist, nlist_data.ilist, + mapping_, dcoord, nloc, nall_real); + } } const std::int64_t node_count = multi_rank ? nall_real : nloc; @@ -823,10 +857,18 @@ void NativeSpinPTExpt::compute(ENERGYVTYPE& ener, graph.edge_index = edges.edge_index; graph.edge_vec = edges.edge_vec; graph.edge_mask = edges.edge_mask; + // Further message-passing blocks refresh the features of the ghost nodes + // of an extended node set from their owners through the swaps of the + // neighbor list; a folded node set holds no ghost nodes. + const bool exchange = multi_rank && canonical_graph_requires_halo(); + const ptexpt::HaloTensors halo = + exchange ? ptexpt::halo_tensors(lmp_list, fwd_map, nloc, device) + : ptexpt::empty_halo(device); std::map output_map = run_graph_payload( graph, node_count, nloc, spin_Tensor.slice(0, 0, node_count), std::vector(fparam.begin(), fparam.end()), - std::vector(aparam_real.begin(), aparam_real.end()), charge_spin); + std::vector(aparam_real.begin(), aparam_real.end()), charge_spin, + exchange ? lmp_list.world : nullptr, &halo); // The forward emits flat per-node public keys; rewrite them into the dense // internal-key layout the extraction below reads. The extended node set @@ -1378,6 +1420,8 @@ void NativeSpinPTExpt::compute_canonical_graph_gpu( const std::int64_t* d_source_row_ptr, const std::int64_t* d_source_order, const float* d_spin, + void* world, + const DP_HaloExchange* halo, const std::int64_t nloc, const std::int64_t nall_nodes, const std::int64_t edge_storage, @@ -1388,6 +1432,23 @@ void NativeSpinPTExpt::compute_canonical_graph_gpu( "archive declares the NeighborGraph lower, which the host entry " "points serve."); } + // Further message-passing blocks read features of the sources of their + // edges, which the halo nodes of a node set receive from their owners + // through its halo exchange; every other model reads none. + const bool reads_halo = canonical_graph_requires_halo(); + if (halo != nullptr && !reads_halo) { + throw deepmd::deepmd_exception( + "compute_canonical_graph_gpu: a halo exchange was given, but the " + "model has no further message-passing blocks that read it."); + } + if (reads_halo && halo == nullptr && nall_nodes > nloc) { + throw deepmd::deepmd_exception( + "compute_canonical_graph_gpu: a model with further message-passing " + "blocks reads features of the halo nodes from their owners, so a node " + "set with " + + std::to_string(nall_nodes - nloc) + + " halo nodes requires its halo exchange."); + } if (!gpu_enabled) { throw deepmd::deepmd_exception( "compute_canonical_graph_gpu requires a CUDA device."); @@ -1474,7 +1535,12 @@ void NativeSpinPTExpt::compute_canonical_graph_gpu( inputs.n_node = torch::full({1}, nall_nodes, opt_i64); inputs.n_local = torch::full({1}, nloc, opt_i64); std::map output; - extract_outputs(output, run_model_canonical(inputs, spin)); + extract_outputs( + output, run_model_canonical(inputs, spin, world, + halo != nullptr + ? ptexpt::halo_tensors( + *halo, device, nloc, nall_nodes) + : ptexpt::empty_halo(device))); auto atom_energy = output["atom_energy"] .reshape({nall_nodes}) .slice(0, 0, nloc) @@ -1505,8 +1571,9 @@ void NativeSpinPTExpt::compute_canonical_graph_gpu( }; // A graph without halo nodes keeps its extents from step to step, so its // evaluation is replayed; a domain's halo changes its extent at every - // neighbor rebuild, so a graph with halo nodes is evaluated eagerly. - if (nloc != nall_nodes) { + // neighbor rebuild, so a graph with halo nodes is evaluated eagerly, as is + // one whose halo exchange communicates between the kernels. + if (nloc != nall_nodes || halo != nullptr) { evaluate(); } else { if (!canonical_replay_) { @@ -1533,6 +1600,10 @@ bool NativeSpinPTExpt::uses_canonical_graph_inference() const { return canonical_abi_; } +bool NativeSpinPTExpt::canonical_graph_requires_halo() const { + return canonical_abi_ && has_message_passing_; +} + // The archive reaches this class only through the scheme dispatch, which // admits nothing but ``spin_scheme == "native"``; both schemas served here // belong to that scheme. diff --git a/source/api_cc/src/commonPTExpt.h b/source/api_cc/src/commonPTExpt.h index 1981531ccf..8713fecd75 100644 --- a/source/api_cc/src/commonPTExpt.h +++ b/source/api_cc/src/commonPTExpt.h @@ -16,12 +16,15 @@ #include #include #include +#include #include +#include #include #include #include #include #include +#include #include #include #include @@ -62,6 +65,153 @@ inline void check_canonical_index(const void* source, } } +/// One directed edge: local endpoints and the extended neighbor's coordinates. +struct ReciprocalEdge { + int center; + int source; + int neighbor; +}; + +/** Match equal-size image lists of opposite directions for one node pair. + * Displacements are recomputed in double precision from the original + * coordinates, avoiding edge-sized geometry storage. Their tolerance includes + * the input rounding of all four coordinates: epsilon(Value) times their + * absolute values bounds cancellation in two independently rounded images. + */ +template +inline bool reciprocal_images_match(const ReciprocalEdge* forward, + const ReciprocalEdge* reverse, + size_t count, + const std::vector& coord) { + const auto opposite = [&](const ReciprocalEdge& a, const ReciprocalEdge& b) { + for (size_t axis = 0; axis < 3; ++axis) { + const double ac = coord[3 * static_cast(a.center) + axis]; + const double an = coord[3 * static_cast(a.neighbor) + axis]; + const double bc = coord[3 * static_cast(b.center) + axis]; + const double bn = coord[3 * static_cast(b.neighbor) + axis]; + const double av = an - ac, bv = bn - bc; + if (!std::isfinite(av) || !std::isfinite(bv)) { + throw deepmd_exception( + "multi-block DPA4C requires finite edge displacements"); + } + const double eps = std::numeric_limits::epsilon(); + const double rounding = eps * std::abs(ac) + eps * std::abs(an) + + eps * std::abs(bc) + eps * std::abs(bn); + if (std::abs(av + bv) > + 2e-6 * (1.0 + std::max(std::abs(av), std::abs(bv))) + rounding) { + return false; + } + } + return true; + }; + if (std::equal(forward, forward + count, reverse, opposite)) { + return true; + } + // Tolerance is not a strict ordering. Augmenting paths match images + // one-to-one even when several candidates fit, preserving multiplicities. + std::vector> adjacent(count); + for (size_t i = 0; i < count; ++i) { + for (size_t j = 0; j < count; ++j) { + if (opposite(forward[i], reverse[j])) { + adjacent[i].push_back(j); + } + } + } + std::vector owner(count, count); + std::function&)> augment = + [&](size_t node, std::vector& seen) { + for (const size_t target : adjacent[node]) { + if (seen[target]) { + continue; + } + seen[target] = true; + if (owner[target] == count || augment(owner[target], seen)) { + owner[target] = node; + return true; + } + } + return false; + }; + for (size_t node = 0; node < count; ++node) { + std::vector seen(count, false); + if (!augment(node, seen)) { + return false; + } + } + return true; +} + +/** Check the global reverse-edge contract at a single-domain list rebuild. + * Each edge stores only three node indices. One sort groups unordered local + * node pairs and separates their two directions. Equal direction counts and + * a one-to-one displacement match establish reciprocity, including duplicate + * periodic images. Self-image edges match against their own negated group. + * The topology builder validates the local-owner mapping before this check. + * Domain-decomposed lists are checked by their producer across ranks instead. + */ +template +inline void check_reciprocal_nlist(const std::vector>& nlist, + const std::vector& centers, + const std::vector& mapping, + const std::vector& coord, + int nloc, + int nall) { + size_t capacity = 0; + for (size_t row = 0; row < nlist.size() && row < centers.size(); ++row) { + if (centers[row] >= 0 && centers[row] < nloc) { + capacity += std::count_if( + nlist[row].begin(), nlist[row].end(), + [nall](int neighbor) { return neighbor >= 0 && neighbor < nall; }); + } + } + std::vector edges; + edges.reserve(capacity); + for (size_t row = 0; row < nlist.size() && row < centers.size(); ++row) { + const int center = centers[row]; + if (center < 0 || center >= nloc) { + continue; + } + for (const int neighbor : nlist[row]) { + if (neighbor >= 0 && neighbor < nall) { + edges.push_back( + {center, static_cast(mapping[neighbor]), neighbor}); + } + } + } + const auto pair_key = [](const ReciprocalEdge& edge) { + const auto endpoints = std::minmax(edge.center, edge.source); + return std::make_tuple(endpoints.first, endpoints.second, edge.center); + }; + std::sort(edges.begin(), edges.end(), [&](const auto& a, const auto& b) { + return pair_key(a) < pair_key(b); + }); + for (size_t begin = 0; begin < edges.size();) { + const auto endpoints = + std::minmax(edges[begin].center, edges[begin].source); + size_t end = begin + 1; + while (end < edges.size() && + std::minmax(edges[end].center, edges[end].source) == endpoints) { + ++end; + } + size_t split = begin; + size_t count = end - begin; + if (endpoints.first != endpoints.second) { + while (split < end && edges[split].center == endpoints.first) { + ++split; + } + count = split - begin; + } + if (count != end - split || + !reciprocal_images_match(edges.data() + begin, edges.data() + split, + count, coord)) { + throw deepmd_exception( + "multi-block DPA4C requires a globally bidirectional graph: " + "each edge must have a reverse edge with opposite displacement"); + } + begin = end; + } +} + /** * @brief Make a caller's accelerator stream current for one scope. * @@ -1146,6 +1296,131 @@ inline std::vector build_comm_tensors_positional_with_virtual_atoms( remapped_recvnum.data(), nlocal, nghost); } +// ============================================================================ +// Halo exchange of a compact canonical node set. +// ============================================================================ + +/** + * @brief The halo exchange of a node set as the compact canonical lower of a + * model with further message-passing blocks receives it + * (source/op/pt/border_exchange.h): the nodes the swaps send, int32 on the + * model device, and the swap table, an int32 CPU tensor of shape + * ``(nswap, 5)`` whose columns are the rank a swap sends to, the rank it + * receives from, the counts of the nodes it sends and receives, and the first + * halo node it receives into. + */ +struct HaloTensors { + at::Tensor send_nodes; + at::Tensor swaps; +}; + +/** + * @brief The halo exchange of a node set without halo nodes, on the model + * device ``device``. + */ +inline HaloTensors empty_halo(const torch::Device& device) { + const auto int32_option = torch::TensorOptions().dtype(torch::kInt32); + return {torch::zeros({0}, int32_option.device(device)), + torch::zeros({0, 5}, int32_option)}; +} + +/** + * @brief The swap table of ``nswap`` swaps (HaloTensors::swaps). + */ +inline at::Tensor halo_swap_table(const int nswap, + const int* sendproc, + const int* recvproc, + const int* sendnum, + const int* recvnum, + const int* firstrecv) { + if (nswap < 0) { + throw deepmd::deepmd_exception( + "the halo exchange has a negative number of swaps."); + } + if (nswap > 0 && + (sendproc == nullptr || recvproc == nullptr || sendnum == nullptr || + recvnum == nullptr || firstrecv == nullptr)) { + throw deepmd::deepmd_exception( + "a nonempty halo exchange requires all five host swap arrays."); + } + auto swaps = + torch::empty({nswap, 5}, torch::TensorOptions().dtype(torch::kInt32)); + int* const table = swaps.data_ptr(); + for (int s = 0; s < nswap; ++s) { + table[5 * s + 0] = sendproc[s]; + table[5 * s + 1] = recvproc[s]; + table[5 * s + 2] = sendnum[s]; + table[5 * s + 3] = recvnum[s]; + table[5 * s + 4] = firstrecv[s]; + } + return swaps; +} + +/** + * @brief The tensors of a halo exchange of the C API, whose send list resides + * on ``device``; the send list is wrapped, not copied. + */ +inline HaloTensors halo_tensors(const DP_HaloExchange& halo, + const torch::Device& device, + std::int64_t nloc, + std::int64_t nall_nodes) { + at::Tensor swaps = + halo_swap_table(halo.nswap, halo.sendproc, halo.recvproc, halo.sendnum, + halo.recvnum, halo.firstrecv); + const std::int64_t owned = halo.nswap == 0 ? nall_nodes : halo.firstrecv[0]; + if (owned != nloc) { + throw deepmd::deepmd_exception( + "the halo plan's owned-node count does not match nloc."); + } + std::int64_t sent = 0; + for (int s = 0; s < halo.nswap; ++s) { + sent += halo.sendnum[s]; + } + if (sent > 0 && halo.d_sendlist == nullptr) { + throw deepmd::deepmd_exception( + "the swaps of the halo exchange send nodes, but its send list is " + "null."); + } + const auto int32_option = + torch::TensorOptions().dtype(torch::kInt32).device(device); + at::Tensor send_nodes = + sent > 0 ? torch::from_blob(const_cast(halo.d_sendlist), {sent}, + int32_option) + : torch::zeros({0}, int32_option); + return {send_nodes, swaps}; +} + +/** + * @brief The halo exchange of the extended node set of a host neighbor list, + * whose ``nloc`` owned nodes precede the ghost atoms that ``fwd_map`` keeps, + * in the order of the atoms. ``fwd_map`` maps an atom to its node, or to -1 + * for an atom of a type the model drops, whose swaps send and receive the + * nodes that remain. The send list is copied to ``device``. + */ +inline HaloTensors halo_tensors(const InputNlist& lmp_list, + const std::vector& fwd_map, + const int nloc, + const torch::Device& device) { + std::vector> sendlist; + std::vector sendnum, recvnum; + remap_comm_sendlist(sendlist, sendnum, recvnum, lmp_list, fwd_map); + std::vector firstrecv(lmp_list.nswap); + std::vector nodes; + int next = nloc; + for (int s = 0; s < lmp_list.nswap; ++s) { + firstrecv[s] = next; + next += recvnum[s]; + nodes.insert(nodes.end(), sendlist[s].begin(), sendlist[s].end()); + } + at::Tensor send_nodes = + torch::from_blob(nodes.data(), {static_cast(nodes.size())}, + torch::TensorOptions().dtype(torch::kInt32)) + .to(device, torch::kInt32, /*non_blocking=*/false, /*copy=*/true); + return {send_nodes, + halo_swap_table(lmp_list.nswap, lmp_list.sendproc, lmp_list.recvproc, + sendnum.data(), recvnum.data(), firstrecv.data())}; +} + // ============================================================================ // Charge-state fold — the runtime charge/spin condition of a compressed model. // ============================================================================ diff --git a/source/api_cc/tests/dpa4c_canonical_test_common.h b/source/api_cc/tests/dpa4c_canonical_test_common.h index 4d6fa22d81..9437169d23 100644 --- a/source/api_cc/tests/dpa4c_canonical_test_common.h +++ b/source/api_cc/tests/dpa4c_canonical_test_common.h @@ -106,6 +106,23 @@ struct Spin { "../../tests/infer/deeppot_dpa4c_canonical_spin.expected"; }; +/// Two-block counterparts whose intermediate features require halo exchange. +template +struct MultiblockPotential : Potential { + static constexpr const char* kModelPath = + "../../tests/infer/deeppot_dpa4c_canonical_multiblock.pt2"; + static constexpr const char* kRefPath = + "../../tests/infer/deeppot_dpa4c_canonical_multiblock.expected"; +}; + +template +struct MultiblockSpin : Spin { + static constexpr const char* kModelPath = + "../../tests/infer/deeppot_dpa4c_canonical_spin_multiblock.pt2"; + static constexpr const char* kRefPath = + "../../tests/infer/deeppot_dpa4c_canonical_spin_multiblock.expected"; +}; + /// Names the instantiations of the cases by their model. struct CaseNames { template @@ -392,6 +409,23 @@ class TestInferDpa4cCanonicalPtExpt : public ::testing::Test { } } + /// Compare an extended graph after folding ghost forces onto their owners. + void expect_folded(const Results& actual, const std::vector& owner) { + EXPECT_LT(max_difference(actual.atom_energy, host.atom_energy), + kReferenceTolerance * largest(host.atom_energy)); + EXPECT_LT(max_difference(fold_onto_owners(actual.force, owner, natoms), + host.force), + kReferenceTolerance * largest(host.force)); + EXPECT_LT(max_difference(actual.virial, host.virial), + kReferenceTolerance * largest(host.virial)); + if constexpr (Case::kSpin) { + EXPECT_LT( + max_difference(fold_onto_owners(actual.force_mag, owner, natoms), + host.force_mag), + kReferenceTolerance * largest(host.force_mag)); + } + } + #if defined(BUILD_PYTORCH) && BUILD_PT_EXPT /// The compact canonical graph that the host entry points build for a /// configuration, on the device. A folded graph holds the local atoms @@ -510,7 +544,8 @@ class TestInferDpa4cCanonicalPtExpt : public ::testing::Test { /// declined. void run_device_entry(void* stream, const bool source_csr = true, - const bool virial = true) { + const bool virial = true, + const DP_HaloExchange* halo = nullptr) { double* const atom_energy = out_atom_energy.data_ptr(); double* const force = out_force.data_ptr(); double* const total_virial = @@ -531,14 +566,15 @@ class TestInferDpa4cCanonicalPtExpt : public ::testing::Test { atom_energy, force, out_force_mag.data_ptr(), total_virial, atom_virial, atype, source, deepmd::canonical_index_width(nodes), edge_vec, destination_row_ptr, source_row_ptr, source_order, - graph_spin.data_ptr(), natoms, nodes, edge_storage, stream); + graph_spin.data_ptr(), /*world=*/nullptr, halo, natoms, nodes, + edge_storage, stream); } else { dp.compute_canonical_graph_gpu( atom_energy, force, total_virial, atom_virial, atype, source, deepmd::canonical_index_width(nodes), edge_vec, destination_row_ptr, source_row_ptr, source_order, - /*d_coord=*/nullptr, /*world=*/nullptr, /*box=*/nullptr, natoms, - nodes, edge_storage, stream); + /*d_coord=*/nullptr, /*world=*/nullptr, halo, + /*box=*/nullptr, natoms, nodes, edge_storage, stream); } } @@ -726,32 +762,17 @@ TYPED_TEST_P(TestInferDpa4cCanonicalPtExpt, // host entry points up to the summation order of the run, which the node // count of the graph configures. const auto graph = this->build_graph(this->system, /*fold=*/false); + ASSERT_FALSE(this->dp.canonical_graph_requires_halo()); this->use_graph(graph); ASSERT_GT(this->nodes, this->natoms); this->allocate_outputs(); - const Results& host = this->host; for (int call = 0; call < 2; ++call) { - const Results halo = this->evaluate(); - const std::string what = "call " + std::to_string(call); - EXPECT_LT(max_difference(halo.atom_energy, host.atom_energy), - kReferenceTolerance * largest(host.atom_energy)) - << what << ": atom energy"; - EXPECT_LT( - max_difference(fold_onto_owners(halo.force, graph.owner, this->natoms), - host.force), - kReferenceTolerance * largest(host.force)) - << what << ": force"; - EXPECT_LT(max_difference(halo.virial, host.virial), - kReferenceTolerance * largest(host.virial)) - << what << ": virial"; - if constexpr (TypeParam::kSpin) { - EXPECT_LT(max_difference( - fold_onto_owners(halo.force_mag, graph.owner, this->natoms), - host.force_mag), - kReferenceTolerance * largest(host.force_mag)) - << what << ": magnetic force"; - } + SCOPED_TRACE("call " + std::to_string(call)); + this->expect_folded(this->evaluate(), graph.owner); } + const DP_HaloExchange unused{}; + EXPECT_THROW(this->run_device_entry(nullptr, true, true, &unused), + std::exception); } TYPED_TEST_P(TestInferDpa4cCanonicalPtExpt, a_capture_elsewhere_stays_valid) { @@ -825,5 +846,50 @@ REGISTER_TYPED_TEST_SUITE_P(TestInferDpa4cCanonicalPtExpt, host_entry_matches_reference); #endif +template +class TestInferDpa4cCanonicalHalo : public TestInferDpa4cCanonicalPtExpt { +}; + +TYPED_TEST_SUITE_P(TestInferDpa4cCanonicalHalo); + +TYPED_TEST_P(TestInferDpa4cCanonicalHalo, + self_exchange_matches_complete_graph) { +#if defined(BUILD_PYTORCH) && BUILD_PT_EXPT + ASSERT_TRUE(this->dp.canonical_graph_requires_halo()); + this->expect_reference(this->host, "default_state"); + const auto graph = this->build_graph(this->system, /*fold=*/false); + this->use_graph(graph); + ASSERT_GT(this->nodes, this->natoms); + this->allocate_outputs(); + + const std::vector owners(graph.owner.begin() + this->natoms, + graph.owner.end()); + const auto sendlist = + torch::tensor(owners, torch::TensorOptions().dtype(torch::kInt32)) + .to(this->graph_atype.device()); + const int rank = 0; + const int ghosts = this->nodes - this->natoms; + const DP_HaloExchange halo{1, + &rank, + &rank, + &ghosts, + &ghosts, + &this->natoms, + sendlist.template data_ptr()}; + for (int call = 0; call < 2; ++call) { + SCOPED_TRACE("call " + std::to_string(call)); + this->reset_outputs(); + this->run_device_entry(nullptr, true, true, &halo); + this->expect_folded(this->read_back(), graph.owner); + } + // A failed C API call stores its error on the handle, so rejection is + // checked after the successful evaluations of that handle. + EXPECT_THROW(this->run_device_entry(nullptr), std::exception); +#endif +} + +REGISTER_TYPED_TEST_SUITE_P(TestInferDpa4cCanonicalHalo, + self_exchange_matches_complete_graph); + } // namespace dpa4c_canonical } // namespace deepmd_test diff --git a/source/api_cc/tests/test_deeppot_dpa4c_canonical_ptexpt.cc b/source/api_cc/tests/test_deeppot_dpa4c_canonical_ptexpt.cc index 31ad21d775..c3bbefde19 100644 --- a/source/api_cc/tests/test_deeppot_dpa4c_canonical_ptexpt.cc +++ b/source/api_cc/tests/test_deeppot_dpa4c_canonical_ptexpt.cc @@ -20,5 +20,12 @@ INSTANTIATE_TYPED_TEST_SUITE_P(CXX, Models, CaseNames); +using HaloModels = ::testing::Types, + MultiblockSpin>; +INSTANTIATE_TYPED_TEST_SUITE_P(CXX, + TestInferDpa4cCanonicalHalo, + HaloModels, + CaseNames); + } // namespace dpa4c_canonical } // namespace deepmd_test diff --git a/source/api_cc/tests/test_deeppot_dpa4c_long_range_ptexpt.cc b/source/api_cc/tests/test_deeppot_dpa4c_long_range_ptexpt.cc index 37b423a59a..983ce5d464 100644 --- a/source/api_cc/tests/test_deeppot_dpa4c_long_range_ptexpt.cc +++ b/source/api_cc/tests/test_deeppot_dpa4c_long_range_ptexpt.cc @@ -617,8 +617,8 @@ class TestInferDeepPotDpa4cLongRangeDevicePtExpt : public ::testing::Test { compact.destination_row_ptr.data_ptr(), source_csr ? compact.source_row_ptr.data_ptr() : nullptr, source_csr ? compact.source_order.data_ptr() : nullptr, - graph.coord.data_ptr(), /*world=*/nullptr, cell, nloc, - graph.nodes, compact.source.size(0), stream); + graph.coord.data_ptr(), /*world=*/nullptr, /*halo=*/nullptr, + cell, nloc, graph.nodes, compact.source.size(0), stream); } // The atomic energies, forces and virial of an evaluation of ``graph`` on diff --git a/source/api_cc/tests/test_deeppot_ptexpt.cc b/source/api_cc/tests/test_deeppot_ptexpt.cc index a8e559d0ee..b2027c0832 100644 --- a/source/api_cc/tests/test_deeppot_ptexpt.cc +++ b/source/api_cc/tests/test_deeppot_ptexpt.cc @@ -98,6 +98,55 @@ deepmd::DeepPot TestInferDeepPotAPtExpt::dp; TYPED_TEST_SUITE(TestInferDeepPotAPtExpt, ValueTypes); #if defined(BUILD_PYTORCH) +template +class TestPtExptReciprocalNlist : public ::testing::Test {}; + +TYPED_TEST_SUITE(TestPtExptReciprocalNlist, ValueTypes); + +TYPED_TEST(TestPtExptReciprocalNlist, PeriodicCoordinateRoundoff) { + std::vector coord{99.9, 0, 0, 0.1, 1, 0, 100.1, 1, 0, -0.1, 0, 0}; + const std::vector mapping{0, 1, 1, 0}; + EXPECT_NO_THROW(deepmd::ptexpt::check_reciprocal_nlist({{2}, {3}}, {0, 1}, + mapping, coord, 2, 4)); + // A geometric mismatch above the coordinate uncertainty is still rejected. + coord[9] = -0.11; + EXPECT_THROW(deepmd::ptexpt::check_reciprocal_nlist({{2}, {3}}, {0, 1}, + mapping, coord, 2, 4), + deepmd::deepmd_exception); +} + +TYPED_TEST(TestPtExptReciprocalNlist, PeriodicImageMultiplicity) { + const std::vector coord{0, 0, 0, 0, 1, 0, 1e-7, 1, + 0, 0, 2, 0, -1e-7, -1, 0}; + const std::vector mapping{0, 1, 1, 1, 0}; + EXPECT_NO_THROW(deepmd::ptexpt::check_reciprocal_nlist( + {{0, 4}, {3, 2}}, {1, 0}, mapping, coord, 2, 5)); + EXPECT_THROW(deepmd::ptexpt::check_reciprocal_nlist({{2, 2}, {0, 4}}, {0, 1}, + mapping, coord, 2, 5), + deepmd::deepmd_exception); + EXPECT_THROW(deepmd::ptexpt::check_reciprocal_nlist({{2, 3}, {0}}, {0, 1}, + mapping, coord, 2, 5), + deepmd::deepmd_exception); + const std::vector self{0, 0, 0, 1, 0, 0, -1, 0, 0}; + EXPECT_NO_THROW(deepmd::ptexpt::check_reciprocal_nlist( + {{1, 2}}, {0}, {0, 0, 0}, self, 1, 3)); + EXPECT_THROW(deepmd::ptexpt::check_reciprocal_nlist({{1, 1}}, {0}, {0, 0, 0}, + self, 1, 3), + deepmd::deepmd_exception); +} + +TYPED_TEST(TestPtExptReciprocalNlist, AmbiguousImagesRequireOneToOneMatching) { + const std::vector coord{0, 0, 0, 0, 0, 0, + 1, 0, 0, 1.000005, 0, 0, + -1.0000025, 0, 0, -0.9999975, 0, 0}; + // The first forward image fits either reverse image. Only the first + // reverse image fits the second forward image, so greedy matching fails. + const deepmd::ptexpt::ReciprocalEdge forward[]{{0, 1, 2}, {0, 1, 3}}; + const deepmd::ptexpt::ReciprocalEdge reverse[]{{1, 0, 4}, {1, 0, 5}}; + EXPECT_TRUE( + deepmd::ptexpt::reciprocal_images_match(forward, reverse, 2, coord)); +} + TEST(TestPtExptMetadata, default_chg_spin_is_optional_when_dim_is_zero) { auto metadata = deepmd::ptexpt::parse_json("{}"); auto value = deepmd::ptexpt::read_default_chg_spin(metadata, 0); diff --git a/source/install/test_cc_local.sh b/source/install/test_cc_local.sh index c1570eec92..b01a09c323 100755 --- a/source/install/test_cc_local.sh +++ b/source/install/test_cc_local.sh @@ -2,7 +2,7 @@ set -ex # With no arguments, build, generate every fixture, and run CTest as before. -# The independent Kokkos job needs the installation and only long-range models. +# The independent Kokkos job needs the installation and its compressed fixtures. MODE=${1:-all} if [ "$#" -gt 1 ]; then echo "Usage: $0 [--build-only | --models-only=kokkos]" >&2 @@ -55,7 +55,7 @@ if [ "$MODE" != "--models-only=kokkos" ]; then -D USE_PT_PYTHON_LIBS=${ENABLE_PYTORCH:-TRUE} \ -D CMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \ -D BUILD_TESTING:BOOL=${BUILD_TESTING} \ - -D LAMMPS_VERSION=stable_22Jul2025_update2 \ + -D LAMMPS_VERSION="${LAMMPS_VERSION:-stable_22Jul2025_update2}" \ ${CUDA_ARGS} .. cmake --build . -j${NPROC} cmake --install . @@ -138,6 +138,7 @@ if [ "${ENABLE_PYTORCH:-TRUE}" == "TRUE" ]; then ${INFER_SCRIPT_PATH}/deeppot_dpa4c_long_range*.pte \ ${INFER_SCRIPT_PATH}/deeppot_dpa4c_long_range*.expected run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_long_range.py --compressed-only + run_generator ${INFER_SCRIPT_PATH}/gen_dpa4c_canonical.py exit 0 fi _FIXTURE_MANIFEST="${INFER_SCRIPT_PATH}/.pt-fixture-cache-manifest" diff --git a/source/install/test_lammps_kokkos.sh b/source/install/test_lammps_kokkos.sh index dbce79fd6e..d425325460 100755 --- a/source/install/test_lammps_kokkos.sh +++ b/source/install/test_lammps_kokkos.sh @@ -45,7 +45,7 @@ MPI_ARGS=( cmake -S "${LAMMPS_SOURCE_ROOT}/cmake" -B "${LAMMPS_BUILD_DIR}" \ -D CMAKE_BUILD_TYPE=Release \ -D CMAKE_CXX_COMPILER="${NVCC_WRAPPER}" \ - -D CMAKE_CXX_STANDARD=17 \ + -D CMAKE_CXX_STANDARD=20 \ -D BUILD_SHARED_LIBS=ON \ -D BUILD_MPI=ON \ -D BUILD_OMP=OFF \ @@ -64,7 +64,7 @@ cmake --build "${LAMMPS_BUILD_DIR}" --target lammps --parallel "${BUILD_JOBS}" cmake -S "${REPO_ROOT}/source" -B "${PLUGIN_BUILD_DIR}" \ -D CMAKE_BUILD_TYPE=Release \ -D CMAKE_CXX_COMPILER="${NVCC_WRAPPER}" \ - -D CMAKE_CXX_STANDARD=17 \ + -D CMAKE_CXX_STANDARD=20 \ -D CMAKE_DISABLE_PRECOMPILE_HEADERS=ON \ -D BUILD_TESTING=OFF \ -D DEEPMD_C_ROOT="${DEEPMD_C_ROOT}" \ @@ -125,6 +125,7 @@ mkdir -p "${BUILD_ROOT}/test-reports" TEST_REPORT_DIR=$(mktemp -d "${BUILD_ROOT}/test-reports/run.XXXXXX") DPA4SPIN_KOKKOS_REQUIRED=1 python -m pytest -v -s \ "${REPO_ROOT}/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py" \ + "${REPO_ROOT}/source/lmp/tests/test_lammps_dpa4c_multiblock_kokkos.py" \ --junitxml="${TEST_REPORT_DIR}/spin.xml" # The compressed long-range fixtures come from gen_dpa4c_long_range.py of # test_cc_local.sh; the MPI runner of the test launches mpirun from PATH, which diff --git a/source/lmp/compact_canonical_graph_kokkos.h b/source/lmp/compact_canonical_graph_kokkos.h index 71321ebc04..c14ee4d208 100644 --- a/source/lmp/compact_canonical_graph_kokkos.h +++ b/source/lmp/compact_canonical_graph_kokkos.h @@ -16,6 +16,12 @@ #include #include +#ifdef LMPPLUGIN +#include "canonical_graph.h" +#else +#include "deepmd/canonical_graph.h" +#endif + #include "atom.h" #include "atom_kokkos.h" #include "atom_masks.h" @@ -85,9 +91,11 @@ __device__ __forceinline__ void compact_canonical_warp_sort(Key (&key)[K], #endif -/// Bits of the candidate slot in the sort keys of the single-pass fill, which -/// serves candidate lists of up to ``1 << kCompactCanonicalSlotBits`` entries. -constexpr int kCompactCanonicalSlotBits = 9; +/// Bits of the candidate slot in the sort keys of the single-pass fill that +/// keys ``K`` candidates per lane: nine for lists of up to 512 candidates and +/// ten for the widest fill, of up to 768. +template +inline constexpr int kCompactCanonicalSlotBits = K > 16 ? 10 : 9; #if defined(KOKKOS_ENABLE_CUDA) // Read the packed record of one atom: its fixed-point coordinates and, in the @@ -290,7 +298,7 @@ __device__ __forceinline__ void compact_canonical_finish_row( const Counts& source_counts) { constexpr unsigned kFull = 0xffffffffu; constexpr std::uint32_t kRejected = ~std::uint32_t{0}; - constexpr int kSlot = kCompactCanonicalSlotBits; + constexpr int kSlot = kCompactCanonicalSlotBits; constexpr std::uint32_t kSlotMask = (1u << kSlot) - 1u; constexpr auto kLaneMajor = CompactCanonicalLayout::kLaneMajor; @@ -484,19 +492,20 @@ __device__ __forceinline__ void compact_canonical_finish_row( // with the capacity and repeats the build with larger arrays. // // The keys of up to ``32 * K`` candidates are formed in the registers of the -// warp: the squared bond length quantized to the 23 bits above the nine bits -// of the candidate slot, which resolves lengths far finer than any thermal -// displacement. A rejected candidate carries the largest key and sorts behind -// every survivor, so the sorted position of a survivor is its slot in the row; -// the survivors are sorted on the fewest registers that hold them. The order -// of the candidates in the neighbor list varies from build to build, and so -// does the order of the local atoms, so survivors of equal quantized length -// are ordered by the tag of their source atom: a row whose sorted keys show -// such a tie is sorted again on 64-bit keys that insert the low 32 bits of the -// tag between the length and the slot. Such ties arise in symmetric -// configurations, such as a perfect lattice, and almost never in a thermal -// one. A row holds every tag once when the box is thicker than twice the -// cutoff along every periodic direction, as the folded node set of a single +// warp: the squared bond length quantized to the bits above those of the +// candidate slot, 23 above nine for lists of up to 512 candidates and 22 +// above ten for the widest fill, either of which resolves lengths far finer +// than any thermal displacement. A rejected candidate carries the largest key +// and sorts behind every survivor, so the sorted position of a survivor is its +// slot in the row; the survivors are sorted on the fewest registers that hold +// them. The order of the candidates in the neighbor list varies from build to +// build, and so does the order of the local atoms, so survivors of equal +// quantized length are ordered by the tag of their source atom: a row whose +// sorted keys show such a tie is sorted again on 64-bit keys that insert the +// low 32 bits of the tag between the length and the slot. Such ties arise in +// symmetric configurations, such as a perfect lattice, and almost never in a +// thermal one. A row holds every tag once when the box is thicker than twice +// the cutoff along every periodic direction, as the folded node set of a single // rank requires, and the row order, and with it the summation order of every // reduction over the row, is then a function of the geometry and the atom // tags alone, which makes the forces reproducible from run to run. In a @@ -555,9 +564,9 @@ KOKKOS_INLINE_FUNCTION void compact_canonical_fill_row( #if defined(KOKKOS_ENABLE_CUDA) && defined(__CUDA_ARCH__) constexpr unsigned kFull = 0xffffffffu; constexpr std::uint32_t kRejected = ~std::uint32_t{0}; + constexpr int kSlot = kCompactCanonicalSlotBits; // Highest length level of a survivor, one below the levels the key holds. - constexpr std::uint32_t kTopLevel = - (std::uint32_t{1} << (32 - kCompactCanonicalSlotBits)) - 2u; + constexpr std::uint32_t kTopLevel = (std::uint32_t{1} << (32 - kSlot)) - 2u; constexpr unsigned long long kInclusive = 1ull << 63; // Candidate slots of one row; the row stride adds four, which spreads the // stores of a warp, eight centers by four slots, over all 32 banks. @@ -573,7 +582,9 @@ KOKKOS_INLINE_FUNCTION void compact_canonical_fill_row( __shared__ int claim; __shared__ int ready; __shared__ alignas(16) int slot_atom[Warps][kSlotStride]; - __shared__ std::uint32_t staging[Warps][256]; + // Survivors that a sort on fewer registers than ``K`` compacts: up to 32 + // times the widest such sort. + __shared__ std::uint32_t staging[Warps][K > 16 ? 512 : 256]; if (rank == 0) { block_ticket = atomicAdd(ticket_counter, 1ull); claim = 0; @@ -682,10 +693,10 @@ KOKKOS_INLINE_FUNCTION void compact_canonical_fill_row( // value. const std::uint32_t level = min(static_cast(length2 * key_scale), kTopLevel); - key[k] = record[u].w >= 0 && length2 < cutsq - ? (level << kCompactCanonicalSlotBits) | - static_cast(k * 32 + lane) - : kRejected; + key[k] = + record[u].w >= 0 && length2 < cutsq + ? (level << kSlot) | static_cast(k * 32 + lane) + : kRejected; count += __popc(__ballot_sync(kFull, key[k] != kRejected)); } } @@ -727,8 +738,12 @@ KOKKOS_INLINE_FUNCTION void compact_canonical_fill_row( DEEPMD_COMPACT_CANONICAL_FINISH(4); } else if (K > 8 && count <= 256u) { DEEPMD_COMPACT_CANONICAL_FINISH(8); - } else { + } else if (K <= 16 || count <= 512u) { DEEPMD_COMPACT_CANONICAL_FINISH((K > 8 ? 16 : 8)); + } else { + if constexpr (K > 16) { + DEEPMD_COMPACT_CANONICAL_FINISH(32); + } } #undef DEEPMD_COMPACT_CANONICAL_FINISH #endif @@ -951,6 +966,78 @@ class CompactCanonicalGhostFold { Kokkos::View h_send, h_recv; }; +// Halo exchange of the extended node set of a decomposed system, the forward +// communication of the Kokkos brick communication in model-node space +// (DP_HaloExchange), which a model with further message-passing blocks reads +// to refresh the features of its ghost nodes from their owners. Without +// virtual atoms the node of every atom of the extended node set is the atom +// itself, so the exchange is the swap plan of the communication, whose send +// lists the exchange gathers into one device list. The plan moves only when +// the borders are rebuilt, together with the neighbor list. +template +class CompactCanonicalHalo { + public: + // The halo exchange of the current borders of ``comm``, rebuilt when + // ``rebuild`` is set, at the step of a neighbor list rebuild, or on the + // first call. + const DP_HaloExchange* plan(Comm* comm, Error* error, const bool rebuild) { + auto* kokkos_comm = dynamic_cast(comm); + if (kokkos_comm == nullptr) { + error->all(FLERR, + "a model with further message-passing blocks exchanges the " + "features of ghost atoms through the swaps of the Kokkos " + "brick communication; use comm_style brick."); + } + if (!rebuild && built) { + return &halo; + } + using Plan = CompactCanonicalSwapPlan; + const int nswap = kokkos_comm->*Plan::swap_count; + const int* plan_sendnum = kokkos_comm->*Plan::send_count; + const int* plan_recvnum = kokkos_comm->*Plan::recv_count; + const int* plan_sendproc = kokkos_comm->*Plan::send_rank; + const int* plan_recvproc = kokkos_comm->*Plan::recv_rank; + const int* plan_firstrecv = kokkos_comm->*Plan::first_recv; + auto& sendlists = kokkos_comm->*Plan::send_lists; + sendproc.assign(plan_sendproc, plan_sendproc + nswap); + recvproc.assign(plan_recvproc, plan_recvproc + nswap); + sendnum.assign(plan_sendnum, plan_sendnum + nswap); + recvnum.assign(plan_recvnum, plan_recvnum + nswap); + firstrecv.assign(plan_firstrecv, plan_firstrecv + nswap); + int total = 0; + for (int iswap = 0; iswap < nswap; ++iswap) { + total += sendnum[iswap]; + } + if (static_cast(d_sendlist.extent(0)) < total) { + d_sendlist = + Kokkos::View("compact_canonical:halo_send", total); + } + sendlists.sync_device(); + auto lists = sendlists.template view(); + auto gathered = d_sendlist; + int offset = 0; + for (int iswap = 0; iswap < nswap; ++iswap) { + Kokkos::parallel_for( + "compact_canonical:halo_send", + Kokkos::RangePolicy(0, sendnum[iswap]), + KOKKOS_LAMBDA(const int i) { + gathered(offset + i) = lists(iswap, i); + }); + offset += sendnum[iswap]; + } + halo = {nswap, sendproc.data(), recvproc.data(), sendnum.data(), + recvnum.data(), firstrecv.data(), d_sendlist.data()}; + built = true; + return &halo; + } + + private: + bool built = false; + std::vector sendproc, recvproc, sendnum, recvnum, firstrecv; + Kokkos::View d_sendlist; + DP_HaloExchange halo = {}; +}; + // Device-resident model node set and compact canonical neighbor graph. // // A ``.pt2`` artifact frozen with the compact canonical lower consumes a @@ -1196,11 +1283,12 @@ class CompactCanonicalGraphKokkos : protected Pointers { // consecutive slots, so the dominant store stream stays coalesced; the // geometry of a survivor is recomputed from its slot, whose coordinates // the key pass has just brought into cache. The single-pass fill keys a - // survivor by its squared length quantized to 23 bits and its slot, and + // survivor by its squared length quantized to 23 bits, or 22 for lists of + // more than 512 candidates, and its slot, and // orders survivors of equal quantized length by tag only in the rows that // hold such ties. The two orders differ. // - // On a CUDA device whose candidate lists fit 512 entries, the warp of a + // On a CUDA device whose candidate lists fit 768 entries, the warp of a // center sorts in registers and the row offsets come from the decoupled // look-back of compact_canonical_fill_row, so counting, offsets and the // fill are one pass. Every other configuration counts the rows first, @@ -1210,8 +1298,10 @@ class CompactCanonicalGraphKokkos : protected Pointers { // so that one 32-byte sector of the neighbor list holds a candidate slot // of every center of the block. constexpr int fill_warps = 8; - static_assert(16 * neighbor_lanes <= (1 << kCompactCanonicalSlotBits), - "the single-pass sort keys must address every candidate"); + static_assert( + 16 * neighbor_lanes <= (1 << kCompactCanonicalSlotBits<16>) && + 24 * neighbor_lanes <= (1 << kCompactCanonicalSlotBits<24>), + "the single-pass sort keys must address every candidate"); const int key_capacity = static_cast(d_neighbors.extent(1)); if (key_capacity >= (1 << 16)) { error->one(FLERR, @@ -1226,18 +1316,32 @@ class CompactCanonicalGraphKokkos : protected Pointers { // and the gathers; one that keys sixteen takes 25 KB, and three teams, 24 // warps, fit. Either bound holds the registers of the whole kernel at the // budget of its common path rather than at that of the rarely taken - // tie-break sort. + // tie-break sort. The widest fill, which keys 24, stages 41 KB, and two + // teams fit. using fill_policy = Kokkos::TeamPolicy< DeviceType, Kokkos::LaunchBounds>; using wide_fill_policy = Kokkos::TeamPolicy< DeviceType, Kokkos::LaunchBounds>; + using widest_fill_policy = Kokkos::TeamPolicy< + DeviceType, + Kokkos::LaunchBounds>; using member_type = typename team_policy::member_type; - // Squared lengths quantize to the key bits above the slot: 23 bits in the - // single-pass fill and 16 bits in the 64-bit keys of the team fill. + // Candidates keyed per lane by the single-pass fill: the fewest of 8, 12, + // 16 and 24 that hold the longest list, or none when the list exceeds 24 + // per lane, which then takes the counted fill. + const int fill_keys = longest_candidates <= 8 * neighbor_lanes ? 8 + : longest_candidates <= 12 * neighbor_lanes ? 12 + : longest_candidates <= 16 * neighbor_lanes ? 16 + : longest_candidates <= 24 * neighbor_lanes ? 24 + : 0; + // Squared lengths quantize to the key bits above the slot: 23 or 22 bits + // in the single-pass fill and 16 bits in the 64-bit keys of the team fill. + const int fill_slot_bits = fill_keys <= 16 ? kCompactCanonicalSlotBits<16> + : kCompactCanonicalSlotBits<24>; const double fill_key_levels = - static_cast((1u << (32 - kCompactCanonicalSlotBits)) - 1u); + static_cast((1u << (32 - fill_slot_bits)) - 1u); const double key_scale = 65535.0 / cutsq; std::int64_t edge_count = 0; // The single-pass fill lays the rows out in the order of the centers and @@ -1250,8 +1354,7 @@ class CompactCanonicalGraphKokkos : protected Pointers { #if defined(KOKKOS_ENABLE_CUDA) single_pass = std::is_same_v && - inum > 0 && inum == atom->nlocal && - longest_candidates <= 16 * neighbor_lanes; + inum > 0 && inum == atom->nlocal && fill_keys > 0; #endif if (single_pass) { // === Pack every atom the fill can visit into one aligned record === @@ -1324,18 +1427,22 @@ class CompactCanonicalGraphKokkos : protected Pointers { } }); const std::int64_t capacity = static_cast(edge_capacity); - if (longest_candidates <= 8 * neighbor_lanes) { + if (fill_keys == 8) { fill_rows<8, fill_warps>( fill_policy(teams, fill_warps * neighbor_lanes), k_list, fill_cutsq, fill_key_scale, vector_scale, source_csr); - } else if (longest_candidates <= 12 * neighbor_lanes) { + } else if (fill_keys == 12) { fill_rows<12, fill_warps>( fill_policy(teams, fill_warps * neighbor_lanes), k_list, fill_cutsq, fill_key_scale, vector_scale, source_csr); - } else { + } else if (fill_keys == 16) { fill_rows<16, fill_warps>( wide_fill_policy(teams, fill_warps * neighbor_lanes), k_list, fill_cutsq, fill_key_scale, vector_scale, source_csr); + } else { + fill_rows<24, fill_warps>( + widest_fill_policy(teams, fill_warps * neighbor_lanes), k_list, + fill_cutsq, fill_key_scale, vector_scale, source_csr); } if (bounded) { break; diff --git a/source/lmp/pair_deepmd_kokkos.cpp b/source/lmp/pair_deepmd_kokkos.cpp index 4fe527b821..a791f48e51 100644 --- a/source/lmp/pair_deepmd_kokkos.cpp +++ b/source/lmp/pair_deepmd_kokkos.cpp @@ -36,6 +36,7 @@ PairDeepMDKokkos::PairDeepMDKokkos(LAMMPS* lmp) edge_vec_fp32(false), canonical_graph(false), canonical_source_csr(false), + canonical_halo(false), device_path_ok(false), reverse_virial(false), reverse_used_host(false) { @@ -222,6 +223,7 @@ void PairDeepMDKokkos::init_style() { edge_vec_fp32 = deep_pot.uses_fp32_edge_vectors(); canonical_graph = deep_pot.uses_canonical_graph_inference(); canonical_source_csr = deep_pot.canonical_graph_requires_source_csr(); + canonical_halo = canonical_graph && deep_pot.canonical_graph_requires_halo(); // PairDeepMD::init_style() has confined a model with a long-range module to // a system periodic in every dimension or in none. The device edge path // passes such a module no cell, so a periodic system reaches it through the @@ -241,6 +243,16 @@ void PairDeepMDKokkos::init_style() { // The model node set is shared by both input schemas; type_idx_map is // populated by the base coeff(). compact_graph.setup(type_idx_map, multi_rank); + // The halo exchange follows the swaps of the communication atom for atom, + // which the nodes of an extended node set do only without virtual atoms. + if (canonical_halo && multi_rank && compact_graph.has_null_types) { + error->all(FLERR, + "pair style deepmd/kk exchanges the features of ghost atoms of " + "a model with further message-passing blocks atom for atom " + "across ranks, which atoms of a type mapped to NULL in " + "pair_coeff break; map every type to an element, or run on a " + "single rank."); + } } template @@ -570,10 +582,19 @@ void PairDeepMDKokkos::compute(int eflag, int vflag) { // A model with a long-range module evaluates the system over all the ranks // that hold it, so on several ranks every rank calls it at every step, one - // without nodes included, and passes it the communicator. - void* const world_ptr = - long_range && multi_rank ? static_cast(&world) : nullptr; - if ((canonical_graph && (nnode_m > 0 || world_ptr != nullptr)) || + // without nodes included, and passes it the communicator. A model with + // further message-passing blocks refreshes the features of the ghost nodes + // from the ranks that own them, through the communicator and the swaps of + // the communication, which a rank without nodes takes no part in. + const DP_HaloExchange* const halo = + canonical_halo && multi_rank + ? halo_exchange.plan(comm, error, neighbor->ago == 0) + : nullptr; + void* const world_ptr = (long_range || halo != nullptr) && multi_rank + ? static_cast(&world) + : nullptr; + const bool joins_long_range = long_range && multi_rank; + if ((canonical_graph && (nnode_m > 0 || joins_long_range)) || (!canonical_graph && (nloc_m > 0 || comm_ptr != nullptr))) { // Fully device-resident inference: raw device pointers in and out. The // compact canonical model is enqueued on the Kokkos stream that builds its @@ -614,7 +635,7 @@ void PairDeepMDKokkos::compute(int eflag, int vflag) { compact_graph.d_destination_row_ptr.data(), source_csr ? compact_graph.d_source_row_ptr.data() : nullptr, source_csr ? compact_graph.d_source_order.data() : nullptr, - coord_ptr, world_ptr, cell_ptr, nloc_m, nnode_m, + coord_ptr, world_ptr, halo, cell_ptr, nloc_m, nnode_m, compact_graph.storage_count, model_stream); } else if (edge_vec_fp32) { deep_pot.compute_edges_gpu(d_atom_energy.data(), d_out_force.data(), diff --git a/source/lmp/pair_deepmd_kokkos.h b/source/lmp/pair_deepmd_kokkos.h index 22e3410132..5b81fc9e2f 100644 --- a/source/lmp/pair_deepmd_kokkos.h +++ b/source/lmp/pair_deepmd_kokkos.h @@ -133,11 +133,16 @@ class PairDeepMDKokkos : public PairDeepMD, public KokkosBase { // The canonical artifact reads the source CSR on every call, not only for // the per-atom virial. bool canonical_source_csr; + // The canonical artifact reads features of the ghost nodes of an extended + // node set from their owners through its halo exchange. + bool canonical_halo; bool device_path_ok; // resolved once in init_style bool reverse_virial; // reverse communication operates on centroid virial bool reverse_used_host; // the host pack/unpack overrides ran // Device-packed fold that replaces the host reverse communication. CompactCanonicalGhostFold ghost_fold; + // Halo exchange of the extended node set for ``canonical_halo``. + CompactCanonicalHalo halo_exchange; }; } // namespace LAMMPS_NS diff --git a/source/lmp/pair_dpa4spin_kokkos.cpp b/source/lmp/pair_dpa4spin_kokkos.cpp index b328e2a3bb..7f7e4636cd 100644 --- a/source/lmp/pair_dpa4spin_kokkos.cpp +++ b/source/lmp/pair_dpa4spin_kokkos.cpp @@ -27,6 +27,7 @@ PairDPA4SpinKokkos::PairDPA4SpinKokkos(LAMMPS* lmp) : PairDPA4Spin(lmp), compact_graph(lmp), multi_rank(false), + canonical_halo(false), reverse_virial(false), reverse_used_host(false) { respa_enable = 0; @@ -181,6 +182,15 @@ void PairDPA4SpinKokkos::init_style() { // Full neighbor-list request and the shared native-spin contract. PairDPA4Spin::init_style(); + // Spatial and spin fields must have independent DualView ownership flags. + // Otherwise clearing magnetic forces can discard migrated atom velocities. + if (((X_MASK | V_MASK | F_MASK) & (SP_MASK | FM_MASK | FML_MASK)) != 0) { + error->all(FLERR, + "pair style dpa4spin/kk requires distinct spatial and spin " + "data masks; use LAMMPS 4 Jul 2026 or newer and rebuild the " + "DeePMD-kit plugin against that LAMMPS build."); + } + // The device-resident entry point runs the model on an accelerator, so the // Kokkos host execution space has nothing to hand it. if (std::is_same::value) { @@ -223,6 +233,17 @@ void PairDPA4SpinKokkos::init_style() { // The model node set is shared with the graph builder; type_idx_map is // populated by the base coeff(). compact_graph.setup(type_idx_map, multi_rank); + // The halo exchange follows the swaps of the communication atom for atom, + // which the nodes of an extended node set do only without virtual atoms. + canonical_halo = deep_spin.canonical_graph_requires_halo(); + if (canonical_halo && multi_rank && compact_graph.has_null_types) { + error->all(FLERR, + "pair style dpa4spin/kk exchanges the features of ghost atoms " + "of a model with further message-passing blocks atom for atom " + "across ranks, which atoms of a type mapped to NULL in " + "pair_coeff break; map every type to an element, or run on a " + "single rank."); + } } template @@ -323,6 +344,15 @@ void PairDPA4SpinKokkos::compute(int eflag, int vflag) { if (model_stream == nullptr) { Kokkos::fence(); } + // A model with further message-passing blocks refreshes the features of + // the ghost nodes from the ranks that own them, through the communicator + // and the swaps of the communication. + const DP_HaloExchange* const halo = + canonical_halo && multi_rank + ? halo_exchange.plan(comm, error, neighbor->ago == 0) + : nullptr; + void* const world_ptr = + halo != nullptr ? static_cast(&world) : nullptr; try { deep_spin.compute_canonical_graph_gpu( d_atom_energy.data(), d_out_force.data(), d_out_force_mag.data(), @@ -332,8 +362,8 @@ void PairDPA4SpinKokkos::compute(int eflag, int vflag) { compact_graph.d_destination_row_ptr.data(), cvflag_atom ? compact_graph.d_source_row_ptr.data() : nullptr, cvflag_atom ? compact_graph.d_source_order.data() : nullptr, - d_moment.data(), nloc_m, nnode_m, compact_graph.storage_count, - model_stream); + d_moment.data(), world_ptr, halo, nloc_m, nnode_m, + compact_graph.storage_count, model_stream); } catch (deepmd_compat::deepmd_exception& e) { error->one(FLERR, e.what()); } diff --git a/source/lmp/pair_dpa4spin_kokkos.h b/source/lmp/pair_dpa4spin_kokkos.h index 794e0c6cd9..c732e1a6ac 100644 --- a/source/lmp/pair_dpa4spin_kokkos.h +++ b/source/lmp/pair_dpa4spin_kokkos.h @@ -89,6 +89,9 @@ class PairDPA4SpinKokkos : public PairDPA4Spin, public KokkosBase { // Model node set and the compact canonical graph over it. CompactCanonicalGraphKokkos compact_graph; bool multi_rank; // domain-decomposed run -> extended (local+ghost) node set + // The artifact reads features of the ghost nodes of an extended node set + // from their owners through its halo exchange. + bool canonical_halo; // (3 * nall) per-node magnetic moment in the ABI's float32 layout, the // LAMMPS unit direction scaled by its magnitude. Kokkos::View d_moment; @@ -120,6 +123,8 @@ class PairDPA4SpinKokkos : public PairDPA4Spin, public KokkosBase { bool reverse_used_host; // the host pack/unpack overrides ran // Device-packed fold that replaces the host reverse communication. CompactCanonicalGhostFold ghost_fold; + // Halo exchange of the extended node set for ``canonical_halo``. + CompactCanonicalHalo halo_exchange; }; } // namespace LAMMPS_NS diff --git a/source/lmp/tests/lammps_test_utils.py b/source/lmp/tests/lammps_test_utils.py index ff73605625..01611d1e0d 100644 --- a/source/lmp/tests/lammps_test_utils.py +++ b/source/lmp/tests/lammps_test_utils.py @@ -20,19 +20,22 @@ Path, ) from typing import ( + TYPE_CHECKING, Any, ) import constants import numpy as np import pytest -from lammps import ( - PyLammps, -) from write_lmp_data import ( write_lmp_data, ) +if TYPE_CHECKING: + from lammps import ( + PyLammps, + ) + def require_backend(environment_variable: str, backend_name: str) -> None: """Skip the current module when its compiled backend is unavailable.""" @@ -80,6 +83,10 @@ def make_atomic_lammps( rejects ``atom_modify map no``; this preserves the no-map failure-path tests used by the graph-model fixtures. """ + from lammps import ( + PyLammps, + ) + if units not in {"metal", "real", "si"}: raise ValueError("units should be metal, real, or si") @@ -109,6 +116,10 @@ def make_spin_lammps( boundary: str = "p p p", ) -> PyLammps: """Create the standard two-type DeepSpin LAMMPS test system.""" + from lammps import ( + PyLammps, + ) + if units != "metal": raise ValueError("units for spin should be metal") diff --git a/source/lmp/tests/run_mpi_dpa4spin_conventions.py b/source/lmp/tests/run_mpi_dpa4spin_conventions.py index d73d3e343f..22485c9e77 100644 --- a/source/lmp/tests/run_mpi_dpa4spin_conventions.py +++ b/source/lmp/tests/run_mpi_dpa4spin_conventions.py @@ -39,10 +39,12 @@ def _pair_pointer(lmp, name, pointer_type): return pointer -def _snapshot(lmp, virial=False): +def _snapshot(lmp: lammps, virial: bool = False) -> dict: + """Collect atom-ID-ordered outputs at the current timestep.""" + # gather() returns atom-ID order, including contributions reverse-communicated # from ghost nodes. All ranks must participate in these collective calls. - def gather(name, count): + def gather(name: str, count: int) -> list[list[float]]: return np.array(lmp.gather(name, 1, count)).reshape(-1, count).tolist() # The pressure compute restricted to the pair reports the global pair @@ -51,6 +53,7 @@ def gather(name, count): pressure = lmp.extract_compute("pvirial", LMP_STYLE_GLOBAL, LMP_TYPE_VECTOR) volume = lmp.get_thermo("vol") / lmp.extract_global("nktv2p") snapshot = { + "step": int(lmp.get_thermo("step")), "ids": list(lmp.gather_atoms("id", 0, 1)), "force": gather("f", 3), "magnetic_force": gather("c_fmprop", 3), @@ -88,12 +91,20 @@ def _cmdargs(kokkos): return cmdargs -def _run(lmp, args, selection, overlay=False): +def _run( + lmp: lammps, + args: argparse.Namespace, + selection: str, + overlay: bool = False, +) -> dict: comm = MPI.COMM_WORLD assert lmp.get_mpi_comm().size == args.ranks pair = "dpa4spin/kk" if args.kokkos else "dpa4spin" atom = "spin/kk" if args.kokkos else "spin" integrator = "verlet/kk" if args.kokkos else "verlet" + # The generic host fix marks all atom arrays as host-modified, including + # magnetic-force DualViews. Kokkos NVE modifies only positions and velocities. + nve_style = "nve/kk" if args.kokkos else "nve" assert lmp.has_style("pair", pair), f"Missing plugin pair style {pair}" pair_args = "" if selection == "default" else f" magnetic_force {selection}" substyle = f"{pair} {args.model.resolve()}{pair_args}" @@ -121,6 +132,11 @@ def _run(lmp, args, selection, overlay=False): "compute fmprop all property/atom fmx fmy fmz", "compute spprop all property/atom spx spy spz sp", "compute pvirial all pressure NULL pair", + *( + ("neigh_modify every 2 delay 0 check no", f"fix integrate all {nve_style}") + if args.cadence + else () + ), "run 0", ): lmp.command(command) @@ -140,6 +156,17 @@ def _run(lmp, args, selection, overlay=False): } assert result["pair_style"] == style assert result["atom_style"] == atom + if args.cadence: + result["neighbor_ages"] = [lmp.extract_setting("neigh_ago")] + result["local_count_history"] = [result["local_counts"]] + for _ in range(3): + lmp.command("run 1 pre no post no") + result["snapshots"].append(_snapshot(lmp)) + result["neighbor_ages"].append(lmp.extract_setting("neigh_ago")) + result["local_count_history"].append( + comm.allgather(lmp.extract_setting("nlocal")) + ) + return result # Repeated computes expose stale ghost magnetic-force accumulation. for _ in range(2): lmp.command("run 0") @@ -169,6 +196,11 @@ def main(): parser.add_argument("output", type=Path) parser.add_argument("--kokkos", action="store_true") parser.add_argument("--ranks", type=int, default=1) + parser.add_argument( + "--cadence", + action="store_true", + help="Run only Cartesian forces over three steps with a two-step neighbor cadence.", + ) args = parser.parse_args() assert MPI.COMM_WORLD.size == args.ranks, ( f"Expected {args.ranks} MPI ranks, got {MPI.COMM_WORLD.size}: " @@ -177,13 +209,18 @@ def main(): results = {} library = None try: - for selection, overlay in ( - ("default", False), - ("precession", False), - ("cartesian", False), - ("precession", True), - ("cartesian", True), - ): + cases = ( + (("cartesian", False),) + if args.cadence + else ( + ("default", False), + ("precession", False), + ("cartesian", False), + ("precession", True), + ("cartesian", True), + ) + ) + for selection, overlay in cases: with lammps(cmdargs=_cmdargs(args.kokkos), comm=MPI.COMM_WORLD) as lmp: library = lmp.lib key = f"overlay_{selection}" if overlay else selection diff --git a/source/lmp/tests/run_mpi_pair_deepmd_dpa3_pt2.py b/source/lmp/tests/run_mpi_pair_deepmd_dpa3_pt2.py index 55d5317943..ac5f2524b5 100644 --- a/source/lmp/tests/run_mpi_pair_deepmd_dpa3_pt2.py +++ b/source/lmp/tests/run_mpi_pair_deepmd_dpa3_pt2.py @@ -1,12 +1,9 @@ # SPDX-License-Identifier: LGPL-3.0-or-later -"""Multi-rank LAMMPS driver for DPA3 .pt2 (Phase 5 of GNN MPI). +"""Multi-rank LAMMPS driver for exported DeePMD energy models. Run via ``mpirun -n N python run_mpi_pair_deepmd_dpa3_pt2.py DATAFILE PB_FILE OUTPUT``. -Mirrors ``run_mpi_pair_deepmd.py`` but targets a GNN model whose .pt2 archive -carries the with-comm artifact (Phase 3 dual-artifact layout). The C++ -``DeepPotPTExpt`` (Phase 4) routes to the with-comm artifact when LAMMPS -reports nswap > 0 (multi-rank), driving MPI ghost-atom exchange via -``deepmd_export::border_op`` per layer. +The C++ backend selects the model's regular, with-comm or compact canonical +entry point and exchanges intermediate features when the model requires it. Rank 0 writes potential energy + per-atom forces (3 cols) + per-atom virial (9 cols, from ``compute centroid/stress/atom NULL pair`` in @@ -22,7 +19,7 @@ import numpy as np from lammps import ( - PyLammps, + lammps, ) from mpi4py import ( MPI, @@ -142,7 +139,15 @@ "device path of LAMMPS + Kokkos runs it without a CUDA-aware MPI. Rank r " "takes device r modulo the visible devices, as DeepPotPTExpt does.", ) +parser.add_argument( + "--check-halo-cadence", + action="store_true", + help="Check owned/ghost participation and the rebuild/reuse sequence of " + "three Kokkos steps with --neigh-every 2.", +) args = parser.parse_args() +if args.check_halo_cadence: + assert args.kokkos and args.nsteps == 3 and args.neigh_every == 2 cmdargs = None if args.kokkos: @@ -151,16 +156,12 @@ devices = min(comm.Get_size(), torch.cuda.device_count()) cmdargs = ["-k", "on", "g", str(devices), "-sf", "kk", "-pk", "kokkos"] cmdargs += ["neigh", "full", "newton", "off", "comm", "host", "gpu/aware", "off"] -lammps = PyLammps(cmdargs=cmdargs) -# Force the requested domain decomposition. The default "2 1 1" -# combined with the simulation box guarantees nswap > 0 on the C++ -# side, so DeepPotPTExpt routes to the with-comm AOTI artifact. Pass -# "1 1 1" to obtain a single-rank reference using the same archive -# (the regular artifact handles nswap==0). -lammps.processors(args.processors) -lammps.units("metal") -lammps.boundary(args.boundary) -lammps.atom_style("atomic") +lmp = lammps(cmdargs=cmdargs) +# Fix the domain decomposition; one rank provides the complete-system reference. +lmp.command(f"processors {args.processors}") +lmp.command("units metal") +lmp.command(f"boundary {args.boundary}") +lmp.command("atom_style atomic") # ``atom_modify map yes`` is required when single-rank dispatch goes # through the regular artifact of a use_loc_mapping=False .pt2: the # C++ side needs the LAMMPS global-id->local-index map to build the @@ -170,83 +171,96 @@ # branches can be exercised — LAMMPS rejects ``atom_modify map no``, # so omitting the command is the only way to leave the map disabled. if not args.no_atom_map: - lammps.atom_modify("map yes") -lammps.neighbor("2.0 bin") -lammps.neigh_modify(f"every {args.neigh_every} delay 0 check no") -lammps.read_data(args.DATAFILE) -lammps.mass("1 16") -lammps.mass("2 2") + lmp.command("atom_modify map yes") +lmp.command("neighbor 2.0 bin") +lmp.command(f"neigh_modify every {args.neigh_every} delay 0 check no") +lmp.command(f"read_data {args.DATAFILE}") +lmp.command("mass 1 16") +lmp.command("mass 2 2") if args.mass3 is not None: # Used by the NULL-type test where the data file has a 3rd LAMMPS # type that maps to a NULL deepmd atype (filtered before model # evaluation). The mass value is physically irrelevant — these # atoms get zero force from the deepmd model. - lammps.mass(f"3 {args.mass3}") -lammps.timestep(0.0005) -lammps.fix("1 all nve") + lmp.command(f"mass 3 {args.mass3}") +lmp.command("timestep 0.0005") +lmp.command("fix 1 all nve") # Initial velocities. Order matters: thermalize real atoms first # (``velocity all create`` would also affect type 3, so we restrict # it to a real-atom group), then set the NULL bias on type 3. if args.real_temp is not None: - lammps.group("realgroup type 1 2") - lammps.velocity(f"realgroup create {args.real_temp:.6f} 12345 mom yes rot yes") + lmp.command("group realgroup type 1 2") + lmp.command(f"velocity realgroup create {args.real_temp:.6f} 12345 mom yes rot yes") if args.null_vx is not None: # Restrict initial velocity to LAMMPS type 3 atoms (NULL-type # in the deepmd plugin's pair_coeff mapping). Real atoms stay # at v=0 (or thermal); only the NULL atoms get the high vx, so # the deepmd model's force outputs on real atoms remain bounded # and the NVE integrator stays stable. - lammps.group("nullgroup type 3") + lmp.command("group nullgroup type 3") if args.null_vx_split: # Send NULL atoms with even/odd LAMMPS atom-id in opposite # directions. Hardcoded to the null_type fixture's NULL ids # (7, 8); sufficient because the runner is only used by this # branch's tests, not as a general utility. - lammps.group("null_id7 id 7") - lammps.group("null_id8 id 8") - lammps.velocity(f"null_id7 set {-args.null_vx:.6f} 0.0 0.0 units box") - lammps.velocity(f"null_id8 set {args.null_vx:.6f} 0.0 0.0 units box") + lmp.command("group null_id7 id 7") + lmp.command("group null_id8 id 8") + lmp.command(f"velocity null_id7 set {-args.null_vx:.6f} 0.0 0.0 units box") + lmp.command(f"velocity null_id8 set {args.null_vx:.6f} 0.0 0.0 units box") else: - lammps.velocity(f"nullgroup set {args.null_vx:.6f} 0.0 0.0 units box") + lmp.command(f"velocity nullgroup set {args.null_vx:.6f} 0.0 0.0 units box") # The Kokkos style is named explicitly, so that a plugin without it fails # instead of falling back to the host style. pair_style_line = f"{'deepmd/kk' if args.kokkos else 'deepmd'} {args.PB_FILE}" if args.pair_extra: pair_style_line += f" {args.pair_extra}" -lammps.pair_style(pair_style_line) -lammps.pair_coeff(args.pair_coeff) +lmp.command(f"pair_style {pair_style_line}") +lmp.command(f"pair_coeff {args.pair_coeff}") # Per-atom virial from the pair contribution. ``centroid/stress/atom`` # is parallel-safe (rank-local data, gathered below). LAMMPS computes # stress*volume per atom in internal units; the parent test reverses # the unit conversion (divide by ``constants.nktv2p``) before comparing # against the reference virial. -lammps.compute("virial all centroid/stress/atom NULL pair") -lammps.run(0) +lmp.command("compute virial all centroid/stress/atom NULL pair") +lmp.command("run 0") # Optional: run additional MD steps to exercise the with-comm # dispatch across neighbor-list rebuilds (LAMMPS rebuilds every # 10 steps with our neigh_modify config, so any nsteps >= 10 # triggers at least one rebuild). -if args.nsteps > 0: - lammps.run(args.nsteps) +if args.check_halo_cadence: + assert lmp.extract_global("pair_style") == "deepmd/kk" + assert lmp.extract_setting("kokkos_active") == 1 + counts = [comm.allgather(lmp.extract_setting("nlocal"))] + assert min(counts[0]) > 0 + if comm.size > 1: + assert min(comm.allgather(lmp.extract_setting("nghost"))) > 0 + ages = [lmp.extract_setting("neigh_ago")] + for _ in range(args.nsteps): + lmp.command("run 1 pre no post no") + ages.append(lmp.extract_setting("neigh_ago")) + counts.append(comm.allgather(lmp.extract_setting("nlocal"))) + assert ages == [0, 1, 0, 1], ages + assert counts[0] == counts[1] and counts[2] == counts[3], counts + if comm.size > 1: + assert counts[0] != counts[2], counts +elif args.nsteps > 0: + lmp.command(f"run {args.nsteps}") -# Forces need to be gathered across ranks. PyLammps's ``atoms[i]`` -# only exposes rank-local atoms; ``gather_atoms`` returns the global, -# id-ordered array on every rank. We also gather ``id`` and reorder +# Gather global arrays on every rank. Also gather ``id`` and reorder # explicitly by id rather than trusting an implicit ordering — this # is robust against subdomain layout, empty subdomains, and any # future LAMMPS change in gather ordering. -forces_global = lammps.lmp.gather_atoms("f", 1, 3) -ids_global = lammps.lmp.gather_atoms("id", 0, 1) +forces_global = lmp.gather_atoms("f", 1, 3) +ids_global = lmp.gather_atoms("id", 0, 1) # Gather the per-atom virial across ranks. ``lmp.gather`` accepts # named per-atom computes (``c_``) and returns the global, # id-ordered array on every rank. -virial_global = lammps.lmp.gather("c_virial", 1, 9) -# ``PyLammps.eval`` is rank-0-only. +virial_global = lmp.gather("c_virial", 1, 9) +pe_global = lmp.get_thermo("pe") +natoms = lmp.get_natoms() if rank == 0: - pe_global = lammps.eval("pe") - natoms = lammps.atoms.natoms forces = np.array(forces_global, dtype=np.float64).reshape(natoms, 3) virials = np.array(virial_global, dtype=np.float64).reshape(natoms, 9) ids = np.array(ids_global, dtype=np.int64).reshape(natoms) @@ -261,8 +275,9 @@ row = np.concatenate([fi, vi]) f.write(" ".join(f"{v:.16e}" for v in row) + "\n") -# Tear down LAMMPS before MPI.Finalize() — see the matching comment in -# ``run_mpi_pair_deepmd_spin_dpa3_pt2.py``. Same teardown-order race -# class; spin happens to hit it more often on CUDA CI. -del lammps +# Release the model and Kokkos runtime before finalizing their communicator. +library = lmp.lib +lmp.close() +if args.kokkos: + library.lammps_kokkos_finalize() MPI.Finalize() diff --git a/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py b/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py index 990d937be6..cd733a16c1 100644 --- a/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py +++ b/source/lmp/tests/test_dpa4spin_kokkos_magnetic_force.py @@ -67,7 +67,7 @@ def _unavailable(reason): @pytest.fixture(scope="module") -def kokkos_model(): +def kokkos_runtime() -> None: # The ordinary LAMMPS suite also runs on CUDA, but uses a non-Kokkos wheel. # Only the dedicated matching library/plugin job opts into this regression. if os.environ.get("DPA4SPIN_KOKKOS_REQUIRED") != "1": @@ -84,6 +84,10 @@ def kokkos_model(): _unavailable(f"Required Python package missing: {module}") if shutil.which(os.environ.get("DPA4SPIN_KOKKOS_MPIEXEC", "mpirun")) is None: _unavailable("mpirun required for the two-rank /kk regression") + + +@pytest.fixture(scope="module") +def kokkos_model(kokkos_runtime: None) -> Path: model = Path(os.environ.get("DPA4SPIN_KOKKOS_MODEL", _MODEL)) if not model.is_file(): _unavailable(f"Generate the compressed canonical fixture first: {model}") @@ -102,7 +106,15 @@ def kokkos_model(): return model -def _run(tmp_path, data, model, *, ranks, kokkos): +def _run( + tmp_path: Path, + data: Path, + model: Path, + *, + ranks: int, + kokkos: bool, + cadence: bool = False, +) -> dict: output = tmp_path / f"{'kokkos' if kokkos else 'host'}-{ranks}.json" runner = Path(__file__).with_name("run_mpi_dpa4spin_conventions.py") command = [ @@ -119,6 +131,8 @@ def _run(tmp_path, data, model, *, ranks, kokkos): ] if kokkos: command.append("--kokkos") + if cadence: + command.append("--cadence") # As in dpa4_spin_harness, bound the whole MPI process group: killing only # mpirun can leave workers holding the pipes open after a timeout. with subprocess.Popen( @@ -158,7 +172,9 @@ def samples(kokkos_model, tmp_path_factory, request): ) -def _assert_snapshot(actual, expected, scale=1.0): +def _assert_snapshot(actual: dict, expected: dict, scale: float = 1.0) -> None: + """Compare outputs at the same timestep using the canonical fp32 tolerances.""" + assert actual["step"] == expected["step"] assert actual["ids"] == expected["ids"] == list(range(1, 7)) np.testing.assert_allclose(actual["spin"], expected["spin"], atol=0, rtol=0) # The canonical kernels use float32; edge/reduction ordering differs between @@ -170,7 +186,11 @@ def _assert_snapshot(actual, expected, scale=1.0): fields.append(("virial", 2e-7)) for name, atol in fields: np.testing.assert_allclose( - actual[name], scale * np.array(expected[name]), rtol=5e-4, atol=atol + actual[name], + scale * np.array(expected[name]), + rtol=5e-4, + atol=atol, + err_msg=f"{name} at step {expected['step']}", ) if "virial" in actual: # The pair fills the global and the per-atom virial from separate @@ -239,6 +259,52 @@ def test_kokkos_conventions_and_mpi(samples): _assert_snapshot(sample["scaled"], first, scale=2.75) +def test_multiblock_halo_survives_neighbor_rebuild( + kokkos_runtime: None, + tmp_path: Path, +) -> None: + """Two ranks exchange active block features on rebuilt and reused lists.""" + model = _MODEL.with_name("deeppot_dpa4c_canonical_spin_multiblock.pt2") + assert model.is_file(), f"Generate the multiblock canonical fixture: {model}" + with zipfile.ZipFile(model) as archive: + metadata = json.loads(archive.read("model/extra/metadata.json")) + assert metadata["lower_input_kind"] == "dpa4c_canonical" + assert metadata["has_message_passing"] + assert not metadata["has_comm_artifact"] + data = tmp_path / "nio.lmp" + coord = _COORD.copy() + # Atom 3 crosses x=7 before the step-2 rebuild. Its 150 Å/ps velocity + # changes the owned-node count and the halo plan on both ranks. + coord[2, 0] = 6.9 + write_lmp_data_spin(_BOX, coord, _SPIN, _TYPE, data) + with data.open("a") as stream: + stream.write("\nVelocities\n\n") + for atom in range(1, len(coord) + 1): + stream.write(f"{atom} {150.0 if atom == 3 else 0.0} 0 0\n") + single, parallel = ( + _run(tmp_path, data, model, ranks=ranks, kokkos=True, cadence=True)["cartesian"] + for ranks in (1, 2) + ) + for ranks, result in ((1, single), (2, parallel)): + assert result["pair_style"] == "dpa4spin/kk" + assert result["kokkos_active"] == 1 + assert len(result["local_counts"]) == ranks + assert sum(result["local_counts"]) == 6 + assert min(result["local_counts"]) > 0 + if ranks == 2: + assert min(result["ghost_counts"]) > 0 + assert result["neighbor_ages"] == [0, 1, 0, 1] + counts = result["local_count_history"] + assert counts[0] == counts[1] and counts[2] == counts[3] + if ranks == 2: + assert counts[2] == [counts[0][0] - 1, counts[0][1] + 1] + for actual, expected in zip( + parallel["snapshots"], single["snapshots"], strict=True + ): + assert np.linalg.norm(expected["magnetic_force"]) > 1e-7 + _assert_snapshot(actual, expected) + + def test_kokkos_overlay_accumulates(samples): host, single, parallel = samples for result in (single, parallel): diff --git a/source/lmp/tests/test_lammps_dpa4c_multiblock_kokkos.py b/source/lmp/tests/test_lammps_dpa4c_multiblock_kokkos.py new file mode 100644 index 0000000000..fcfeea6356 --- /dev/null +++ b/source/lmp/tests/test_lammps_dpa4c_multiblock_kokkos.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Kokkos halo exchange for an active two-block canonical energy model.""" + +import json +import os +import zipfile +from pathlib import ( + Path, +) + +import constants +import numpy as np +import pytest +from expected_ref import ( + read_expected_ref, +) +from lammps_test_utils import ( + run_mpi_pair_runner, +) +from write_lmp_data import ( + write_lmp_data, +) + + +def test_multiblock_halo_survives_neighbor_rebuild(tmp_path: Path) -> None: + """Owned and ghost rows agree with one rank across rebuild and reuse.""" + if os.environ.get("DPA4SPIN_KOKKOS_REQUIRED") != "1": + pytest.skip("Enable the dedicated CUDA Kokkos plugin regression explicitly") + infer = Path(__file__).resolve().parents[2] / "tests/infer" + model = infer / "deeppot_dpa4c_canonical_multiblock.pt2" + assert model.is_file(), f"Generate the multiblock canonical fixture: {model}" + with zipfile.ZipFile(model) as archive: + metadata = json.loads(archive.read("model/extra/metadata.json")) + assert metadata["lower_input_kind"] == "dpa4c_canonical" + assert metadata["has_message_passing"] + assert not metadata["has_comm_artifact"] + system = read_expected_ref(model.with_suffix(".expected"))["system"] + cell = system["box"].reshape(3, 3) + box = np.array([0, cell[0, 0], 0, cell[1, 1], 0, cell[2, 2], 0, 0, 0]) + coord = system["coord"].reshape(-1, 3).copy() + # Atom 10 crosses the x-domain boundary before the step-2 rebuild, + # changing the owned prefix and invalidating the previous halo plan. + coord[9, 0] = cell[0, 0] / 2 - 0.1 + data = tmp_path / "lattice.lmp" + write_lmp_data(box, coord, system["atype"].astype(int) + 1, data) + with data.open("a") as stream: + stream.write("\nVelocities\n\n") + for atom in range(1, len(coord) + 1): + stream.write(f"{atom} {150.0 if atom == 10 else 0.0} 0 0\n") + runner = Path(__file__).with_name("run_mpi_pair_deepmd_dpa3_pt2.py") + single, parallel = ( + run_mpi_pair_runner( + runner, + data, + model, + nprocs=ranks, + processors=f"{ranks} 1 1", + runner_args=[ + "--kokkos", + "--nsteps", + "3", + "--neigh-every", + "2", + "--check-halo-cadence", + ], + timeout=600, + ) + for ranks in (1, 2) + ) + assert parallel["pe"] == pytest.approx(single["pe"], rel=1e-5, abs=1e-5) + np.testing.assert_allclose( + parallel["forces"], single["forces"], rtol=1e-4, atol=1e-5 + ) + np.testing.assert_allclose( + parallel["virials"] / constants.nktv2p, + single["virials"] / constants.nktv2p, + rtol=1e-4, + atol=1e-5, + ) diff --git a/source/op/pt/CMakeLists.txt b/source/op/pt/CMakeLists.txt index 4c7e4e29d1..fba81a57db 100644 --- a/source/op/pt/CMakeLists.txt +++ b/source/op/pt/CMakeLists.txt @@ -208,14 +208,42 @@ if(USE_CUDA_TOOLKIT AND DEEPMD_TORCH_HAS_CUDA) "${DPA4C_SHARD_WIDTH}, ${DPA4C_SHARD_LMAX}>(\n" " const Arguments& arguments, cudaStream_t stream);\n") endforeach() + string( + APPEND + DPA4C_SHARD_INSTANTIATIONS + "template void launch_first_stage<" + "${DPA4C_SHARD_WIDTH}, ${DPA4C_SHARD_LMAX}>(\n" + " FirstStage stage, const Arguments& arguments,\n" + " cudaStream_t stream);\n") + string( + APPEND + DPA4C_BLOCK_SHARD_INSTANTIATIONS + "template void launch_block<" + "${DPA4C_SHARD_WIDTH}, ${DPA4C_SHARD_LMAX}>(\n" + " BlockStage stage, const BlockArguments& arguments,\n" + " cudaStream_t stream);\n") endforeach() set(DPA4C_SHARD "${DPA4C_GENERATED_DIR}/c${DPA4C_SHARD_WIDTH}_l${DPA4C_SHARD_GROUP}.cu" ) configure_file(dpa4c/shard.cu.in "${DPA4C_SHARD}" @ONLY) list(APPEND DPA4C_GRAPH_COMPRESS_KERNEL_SRC "${DPA4C_SHARD}") + # The kernels of the further message-passing blocks are instantiated in + # shards of their own, which compile beside those of the first block. + set(DPA4C_SHARD_INSTANTIATIONS "${DPA4C_BLOCK_SHARD_INSTANTIATIONS}") + set(DPA4C_KERNEL_HEADER_SAVED "${DPA4C_KERNEL_HEADER}") + set(DPA4C_KERNEL_HEADER + "${CMAKE_CURRENT_SOURCE_DIR}/dpa4c/block_kernel.cuh") + set(DPA4C_SHARD + "${DPA4C_GENERATED_DIR}/c${DPA4C_SHARD_WIDTH}_l${DPA4C_SHARD_GROUP}_block.cu" + ) + configure_file(dpa4c/shard.cu.in "${DPA4C_SHARD}" @ONLY) + list(APPEND DPA4C_GRAPH_COMPRESS_KERNEL_SRC "${DPA4C_SHARD}") + set(DPA4C_KERNEL_HEADER "${DPA4C_KERNEL_HEADER_SAVED}") + unset(DPA4C_BLOCK_SHARD_INSTANTIATIONS) endforeach() endforeach() + unset(DPA4C_KERNEL_HEADER_SAVED) unset(DPA4C_SHARD) unset(DPA4C_SHARD_DIRECTION) unset(DPA4C_SHARD_LMAX) @@ -243,6 +271,7 @@ if(USE_CUDA_TOOLKIT AND DEEPMD_TORCH_HAS_CUDA) edge_force_virial.cu long_range/direct_sum.cu long_range/domain_exchange.cc + border_exchange.cc long_range/latent_charge_sum.cu long_range/mesh_sum.cu dpa1_graph_energy_force.cu diff --git a/source/op/pt/border_exchange.cc b/source/op/pt/border_exchange.cc new file mode 100644 index 0000000000..4b461ebba4 --- /dev/null +++ b/source/op/pt/border_exchange.cc @@ -0,0 +1,354 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// Device-resident border exchange (contract in border_exchange.h). +// +// The rows a swap sends are gathered on the device into one contiguous +// buffer. With an MPI library that reads device memory they travel from that +// buffer into the halo rows directly; otherwise they are staged through pinned +// host buffers. A swap of rows of this rank copies them on the device. + +#include "border_exchange.h" + +#include +#include +#include + +#include +#include +#include + +#include "communicator.h" + +namespace deepmd { +namespace { + +/// Tag of the messages of a border exchange. Messages between two ranks are +/// received in the order they are sent, so one tag serves every swap. +constexpr int kBorderTag = 0x4450; + +struct Swap { + int send_rank; + int receive_rank; + std::int64_t send_count; + std::int64_t receive_count; + std::int64_t first_receive; +}; + +Swap swap_at(const torch::Tensor& swaps, std::int64_t index) { + const int* row = swaps.data_ptr() + index * kBorderSwapColumns; + return {row[kBorderSendRank], row[kBorderReceiveRank], row[kBorderSendCount], + row[kBorderReceiveCount], row[kBorderFirstReceive]}; +} + +} // namespace + +std::int64_t check_border_plan(const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator, + std::int64_t node_count, + const char* op) { + TORCH_CHECK(swaps.device().is_cpu() && swaps.scalar_type() == torch::kInt32 && + swaps.dim() == 2 && swaps.size(1) == kBorderSwapColumns && + swaps.is_contiguous(), + op, + ": the border swaps must be a contiguous int32 CPU tensor of " + "shape (nswap, ", + static_cast(kBorderSwapColumns), ")"); + TORCH_CHECK(send_nodes.is_cuda() && send_nodes.dim() == 1 && + send_nodes.scalar_type() == torch::kInt32 && + send_nodes.is_contiguous(), + op, + ": the border send list must be a contiguous int32 CUDA " + "vector"); + communicator_address(communicator, op); + TORCH_CHECK(node_count <= std::numeric_limits::max(), op, + ": a border exchange addresses its rows with int32 indices, but " + "the node set holds ", + node_count, " rows"); + const std::int64_t owned = + swaps.size(0) == 0 ? node_count : swap_at(swaps, 0).first_receive; + std::int64_t next = owned; + std::int64_t sent = 0; + for (std::int64_t s = 0; s < swaps.size(0); ++s) { + const Swap swap = swap_at(swaps, s); + TORCH_CHECK(swap.send_count >= 0 && swap.receive_count >= 0, op, ": swap ", + s, " of the border plan has a negative row count"); + TORCH_CHECK(swap.first_receive == next, op, ": swap ", s, + " of the border plan receives into the rows from ", + swap.first_receive, ", but the halo rows before it end at ", + next); + next += swap.receive_count; + sent += swap.send_count; + } + TORCH_CHECK(owned >= 0 && next == node_count, op, + ": the swaps of the border plan fill the rows from ", owned, + " up to ", next, ", but the node set holds ", node_count, + " rows"); + TORCH_CHECK(send_nodes.numel() >= sent, op, + ": the swaps of the border plan " + "send ", + sent, " rows, but the send list holds ", send_nodes.numel()); + std::int64_t offset = 0; + for (std::int64_t s = 0; s < swaps.size(0); ++s) { + const Swap swap = swap_at(swaps, s); + const auto indices = send_nodes.slice(0, offset, offset + swap.send_count); + at::_assert_async( + ((indices >= 0) & (indices < swap.first_receive)).all(), + "a border swap must send only owned or earlier-received rows"); + offset += swap.send_count; + } + return owned; +} + +void border_exchange(const torch::Tensor& rows, + const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator) { + const std::int64_t nswap = swaps.size(0); + if (nswap == 0) { + return; + } + TORCH_CHECK(rows.is_cuda() && rows.dim() == 2 && + rows.scalar_type() == torch::kFloat32 && rows.is_contiguous(), + "border_exchange: the rows must be a contiguous float32 CUDA " + "matrix"); + const std::int64_t width = rows.size(1); + const std::int64_t address = + communicator_address(communicator, "border_exchange"); + int rank = 0; +#ifdef USE_MPI + MPI_Comm comm = MPI_COMM_NULL; + MPI_Datatype row_type = MPI_DATATYPE_NULL; + if (address != 0) { + comm = communicator_handle(communicator, "border_exchange"); + MPI_Comm_rank(comm, &rank); + } +#endif + std::int64_t largest = 0; + for (std::int64_t s = 0; s < nswap; ++s) { + const Swap swap = swap_at(swaps, s); + largest = std::max({largest, swap.send_count, swap.receive_count}); + } + auto packed = torch::empty({largest, width}, rows.options()); + torch::Tensor host_send; + torch::Tensor host_receive; + std::int64_t offset = 0; + for (std::int64_t s = 0; s < nswap; ++s) { + const Swap swap = swap_at(swaps, s); + const torch::Tensor sent = send_nodes.narrow(0, offset, swap.send_count); + offset += swap.send_count; + auto send_rows = packed.narrow(0, 0, swap.send_count); + auto receive_rows = rows.narrow(0, swap.first_receive, swap.receive_count); + if (swap.send_rank == rank && swap.receive_rank == rank) { + TORCH_CHECK(swap.send_count == swap.receive_count, + "border_exchange: self swap ", s, " sends ", swap.send_count, + " rows but receives ", swap.receive_count); + at::index_select_out(send_rows, rows, 0, sent); + receive_rows.copy_(send_rows); + continue; + } +#ifdef USE_MPI + TORCH_CHECK(address != 0, "border_exchange: swap ", s, " involves rank ", + swap.send_rank, " or ", swap.receive_rank, + ", but no communicator was given"); + if (row_type == MPI_DATATYPE_NULL) { + MPI_Type_contiguous(static_cast(width), MPI_FLOAT, &row_type); + MPI_Type_commit(&row_type); + } + TORCH_CHECK(swap.send_count <= std::numeric_limits::max() && + swap.receive_count <= std::numeric_limits::max(), + "border_exchange: a swap exceeds the int range of an MPI " + "count"); + if (swap.send_count > 0) { + at::index_select_out(send_rows, rows, 0, sent); + } + MPI_Request requests[2]; + int pending = 0; + if (mpi_reads_device_memory()) { + // MPI reads the rows of the device once the stream has written them. + at::cuda::getCurrentCUDAStream().synchronize(); + if (swap.receive_count > 0) { + MPI_Irecv(receive_rows.data_ptr(), + static_cast(swap.receive_count), row_type, + swap.receive_rank, kBorderTag, comm, &requests[pending++]); + } + if (swap.send_count > 0) { + MPI_Isend(send_rows.data_ptr(), + static_cast(swap.send_count), row_type, swap.send_rank, + kBorderTag, comm, &requests[pending++]); + } + MPI_Waitall(pending, requests, MPI_STATUSES_IGNORE); + continue; + } + if (!host_send.defined()) { + const auto pinned = + rows.options().device(torch::kCPU).pinned_memory(true); + host_send = torch::empty({largest, width}, pinned); + host_receive = torch::empty({largest, width}, pinned); + } + auto staged_send = host_send.narrow(0, 0, swap.send_count); + auto staged_receive = host_receive.narrow(0, 0, swap.receive_count); + if (swap.send_count > 0) { + // A blocking copy waits for the stream, so the staged rows are complete. + staged_send.copy_(send_rows); + } + if (swap.receive_count > 0) { + MPI_Irecv(staged_receive.data_ptr(), + static_cast(swap.receive_count), row_type, + swap.receive_rank, kBorderTag, comm, &requests[pending++]); + } + if (swap.send_count > 0) { + MPI_Isend(staged_send.data_ptr(), + static_cast(swap.send_count), row_type, swap.send_rank, + kBorderTag, comm, &requests[pending++]); + } + MPI_Waitall(pending, requests, MPI_STATUSES_IGNORE); + if (swap.receive_count > 0) { + receive_rows.copy_(staged_receive, /*non_blocking=*/true); + // The pinned buffer is rewritten by the next swap, so its copy to the + // device completes before the host reuses it. + at::cuda::getCurrentCUDAStream().synchronize(); + } +#else + TORCH_CHECK(false, "border_exchange: swap ", s, " involves rank ", + swap.send_rank, " or ", swap.receive_rank, + ", which requires DeePMD-kit built with MPI"); +#endif + } +#ifdef USE_MPI + if (row_type != MPI_DATATYPE_NULL) { + MPI_Type_free(&row_type); + } +#endif +} + +void border_accumulate(const torch::Tensor& rows, + const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator) { + const std::int64_t nswap = swaps.size(0); + if (nswap == 0) { + return; + } + TORCH_CHECK(rows.is_cuda() && rows.dim() == 2 && + rows.scalar_type() == torch::kFloat32 && rows.is_contiguous(), + "border_accumulate: the rows must be a contiguous float32 CUDA " + "matrix"); + const std::int64_t width = rows.size(1); + const std::int64_t address = + communicator_address(communicator, "border_accumulate"); + int rank = 0; +#ifdef USE_MPI + MPI_Comm comm = MPI_COMM_NULL; + MPI_Datatype row_type = MPI_DATATYPE_NULL; + if (address != 0) { + comm = communicator_handle(communicator, "border_accumulate"); + MPI_Comm_rank(comm, &rank); + } +#endif + std::int64_t largest = 0; + std::vector offsets(nswap + 1, 0); + for (std::int64_t s = 0; s < nswap; ++s) { + const Swap swap = swap_at(swaps, s); + largest = std::max({largest, swap.send_count, swap.receive_count}); + offsets[s + 1] = offsets[s] + swap.send_count; + } + auto packed = torch::empty({largest, width}, rows.options()); + torch::Tensor host_send; + torch::Tensor host_receive; + for (std::int64_t s = nswap - 1; s >= 0; --s) { + const Swap swap = swap_at(swaps, s); + const torch::Tensor sent = + send_nodes.narrow(0, offsets[s], swap.send_count); + const auto halo_rows = + rows.narrow(0, swap.first_receive, swap.receive_count); + if (swap.send_rank == rank && swap.receive_rank == rank) { + TORCH_CHECK(swap.send_count == swap.receive_count, + "border_accumulate: self swap ", s, " sends ", + swap.send_count, " rows but receives ", swap.receive_count); + // The addition reads its source apart from the rows it adds onto, so + // the halo rows are copied first. + auto returned = packed.narrow(0, 0, swap.receive_count); + returned.copy_(halo_rows); + rows.index_add_(0, sent, returned); + continue; + } +#ifdef USE_MPI + TORCH_CHECK(address != 0, "border_accumulate: swap ", s, " involves rank ", + swap.send_rank, " or ", swap.receive_rank, + ", but no communicator was given"); + if (row_type == MPI_DATATYPE_NULL) { + MPI_Type_contiguous(static_cast(width), MPI_FLOAT, &row_type); + MPI_Type_commit(&row_type); + } + TORCH_CHECK(swap.send_count <= std::numeric_limits::max() && + swap.receive_count <= std::numeric_limits::max(), + "border_accumulate: a swap exceeds the int range of an MPI " + "count"); + // The halo rows travel back to the rank they came from, and the rows this + // rank sent return from the rank it sent them to. + auto returned = packed.narrow(0, 0, swap.send_count); + MPI_Request requests[2]; + int pending = 0; + if (mpi_reads_device_memory()) { + at::cuda::getCurrentCUDAStream().synchronize(); + if (swap.send_count > 0) { + MPI_Irecv(returned.data_ptr(), static_cast(swap.send_count), + row_type, swap.send_rank, kBorderTag, comm, + &requests[pending++]); + } + if (swap.receive_count > 0) { + MPI_Isend(halo_rows.data_ptr(), + static_cast(swap.receive_count), row_type, + swap.receive_rank, kBorderTag, comm, &requests[pending++]); + } + MPI_Waitall(pending, requests, MPI_STATUSES_IGNORE); + } else { + if (!host_send.defined()) { + const auto pinned = + rows.options().device(torch::kCPU).pinned_memory(true); + host_send = torch::empty({largest, width}, pinned); + host_receive = torch::empty({largest, width}, pinned); + } + auto staged_send = host_send.narrow(0, 0, swap.receive_count); + auto staged_receive = host_receive.narrow(0, 0, swap.send_count); + if (swap.receive_count > 0) { + // A blocking copy waits for the stream, so the staged rows are + // complete. + staged_send.copy_(halo_rows); + } + if (swap.send_count > 0) { + MPI_Irecv(staged_receive.data_ptr(), + static_cast(swap.send_count), row_type, swap.send_rank, + kBorderTag, comm, &requests[pending++]); + } + if (swap.receive_count > 0) { + MPI_Isend(staged_send.data_ptr(), + static_cast(swap.receive_count), row_type, + swap.receive_rank, kBorderTag, comm, &requests[pending++]); + } + MPI_Waitall(pending, requests, MPI_STATUSES_IGNORE); + if (swap.send_count > 0) { + returned.copy_(staged_receive, /*non_blocking=*/true); + // The pinned buffer is rewritten by the next swap, so its copy to the + // device completes before the host reuses it. + at::cuda::getCurrentCUDAStream().synchronize(); + } + } + if (swap.send_count > 0) { + rows.index_add_(0, sent, returned); + } +#else + TORCH_CHECK(false, "border_accumulate: swap ", s, " involves rank ", + swap.send_rank, " or ", swap.receive_rank, + ", which requires DeePMD-kit built with MPI"); +#endif + } +#ifdef USE_MPI + if (row_type != MPI_DATATYPE_NULL) { + MPI_Type_free(&row_type); + } +#endif +} + +} // namespace deepmd diff --git a/source/op/pt/border_exchange.h b/source/op/pt/border_exchange.h new file mode 100644 index 0000000000..74b5a4aac4 --- /dev/null +++ b/source/op/pt/border_exchange.h @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// Device-resident border exchange of a domain-decomposed system: the forward +// communication of border_op, with the send lists on the device, and its +// reverse, which accumulates the halo rows onto their atoms. +// +// The node set of a domain holds its owned rows first, then its halo rows, +// which images of atoms that other swaps deliver. A plan describes the swaps +// of a LAMMPS brick decomposition in model-node space: +// +// swaps int32 CPU tensor of shape (nswap, kBorderSwapColumns). Swap s +// sends ``swaps[s, kBorderSendCount]`` rows to rank +// ``swaps[s, kBorderSendRank]`` and receives +// ``swaps[s, kBorderReceiveCount]`` rows from rank +// ``swaps[s, kBorderReceiveRank]`` into the consecutive rows +// from ``swaps[s, kBorderFirstReceive]``. The first swap +// receives into the first halo row, every further swap into the +// row after those of the swap before it, and the swaps together +// fill every halo row. +// send_nodes int32 CUDA tensor holding the rows sent in every swap, the +// swaps concatenated in order. A swap may send a halo row that +// an earlier swap received. +// communicator int64 CPU tensor of one element holding the address of the +// MPI_Comm handle of the caller (communicator.h), zero for a +// single process, whose swaps are all self swaps. +// +// A self swap, whose two ranks are this rank, copies the rows on the device. +// The swaps run in order, so the halo rows of an image of an image are filled +// after the rows they copy. Messages of zero rows are never posted, so a rank +// whose swaps carry no rows need not take part. + +#pragma once + +#include + +#include + +namespace deepmd { + +/// Columns of a row of the swap table of a border plan. +enum BorderSwapColumn : int { + kBorderSendRank = 0, + kBorderReceiveRank = 1, + kBorderSendCount = 2, + kBorderReceiveCount = 3, + kBorderFirstReceive = 4, + kBorderSwapColumns = 5, +}; + +/// Check that a border plan fills the halo rows of a node set of +/// ``node_count`` rows, that its send list holds the rows of every swap and +/// that its communicator is well formed, and return the owned row count of +/// the node set: the first row the first swap receives into, or +/// ``node_count`` for a plan without swaps. ``op`` names the caller in the +/// error messages. +std::int64_t check_border_plan(const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator, + std::int64_t node_count, + const char* op); + +/// Replace every halo row of ``rows``, a contiguous float32 CUDA matrix of +/// shape (node_count, W), by the row of the atom it images, swap by swap. The +/// host waits for the current stream once before every swap that MPI carries, +/// so that MPI reads complete rows; the received rows reach the device in +/// stream order. +void border_exchange(const torch::Tensor& rows, + const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator); + +/// The reverse of border_exchange: add every halo row of ``rows`` onto the row +/// of the atom it images, swap by swap in reverse order, so that a halo row +/// that a later swap sent on receives the additions of its own images before +/// it adds onto the row it was copied from. The halo rows keep their values. +/// A swap of a LAMMPS plan sends every row at most once, so every row receives +/// at most one addition per swap and the sums do not depend on the order of +/// the device atomics. +void border_accumulate(const torch::Tensor& rows, + const torch::Tensor& send_nodes, + const torch::Tensor& swaps, + const torch::Tensor& communicator); + +} // namespace deepmd diff --git a/source/op/pt/communicator.h b/source/op/pt/communicator.h new file mode 100644 index 0000000000..b89ac8164d --- /dev/null +++ b/source/op/pt/communicator.h @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// The MPI communicator of a decomposed system, as the operators receive it: an +// int64 CPU tensor of one element that holds the address of the caller's +// MPI_Comm handle, or zero for a single process. The handle is read with the +// width of MPI_Comm of the MPI library the operators are built against: an int +// in MPICH, a pointer in Open MPI. + +#pragma once + +#include +#include + +#include + +#ifdef USE_MPI +#include +#ifdef OMPI_MPI_H +#include +#endif +#endif + +namespace deepmd { + +/// The address held by ``communicator``, zero for a single process. +inline std::int64_t communicator_address(const torch::Tensor& communicator, + const char* op) { + TORCH_CHECK(communicator.device().is_cpu() && + communicator.scalar_type() == torch::kInt64 && + communicator.numel() == 1, + op, + ": the communicator must be an int64 CPU tensor of one element"); + return communicator.contiguous().data_ptr()[0]; +} + +#ifdef USE_MPI +/// The MPI_Comm handle at the address held by ``communicator``. +inline MPI_Comm communicator_handle(const torch::Tensor& communicator, + const char* op) { + static_assert(sizeof(std::uintptr_t) <= sizeof(std::int64_t), + "an address must fit in an int64 tensor"); + const std::int64_t address = communicator_address(communicator, op); + TORCH_CHECK(address != 0, op, ": the communicator holds no handle"); + int initialized = 0; + MPI_Initialized(&initialized); + TORCH_CHECK(initialized != 0, op, + ": a communicator was given, but MPI is not initialized"); + return *reinterpret_cast( + static_cast(address)); +} + +/// Whether the MPI library reads and writes device memory. +inline bool mpi_reads_device_memory() { +#ifdef NO_CUDA_AWARE + return false; +#else + return MPIX_Query_cuda_support() != 0; +#endif +} +#endif + +} // namespace deepmd diff --git a/source/op/pt/dpa4c/block_kernel.cuh b/source/op/pt/dpa4c/block_kernel.cuh new file mode 100644 index 0000000000..4c80711bad --- /dev/null +++ b/source/op/pt/dpa4c/block_kernel.cuh @@ -0,0 +1,3072 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// Device templates of the further message-passing blocks of the compressed +// DPA4C descriptor (stages, buffers and record layout in block_launch.h; the +// equations in deepmd/pt_expt/kernels/dpa4c/attention.py). +// +// The edge stages scan panels of consecutive edges of a block of destination +// rows. Every lane of a block owns the same tile of edges and channels in every +// per-edge quantity of a panel, so the amplitudes, the activations and their +// cotangents stay in registers from the table lookup through both edge maps, +// whose contractions read their operand, feature-major, from shared memory: +// the hidden layer reads the fields and the saturated amplitudes through +// [W_F; W_phi], the logit the fields and the activated hidden layer through +// [G; W_O]. The sums over the edges of a row take a few consecutive lanes per +// value, each summing a fixed residue class of the edges of the row, and add +// the lanes of a value in a fixed butterfly (add_row_sums). +// +// The backward scans the rows of the sources. A compact canonical graph lists +// every bond in both directions with opposite vectors, so the entries of the +// row of node j are the edges j emits, read with the reversed vector and the +// reversed type pair. The row then owns the cotangent of its source features +// and accumulates it in fixed order, while the destination cotangents that the +// edges read are gathered from their nodes and the force on the destination +// lands in fixed point, as in the first block. + +#pragma once + +#include + +#include +#include +#include +#include +#include + +#include "../simt_gemm.cuh" +#include "block_launch.h" +#include "graph_compress.cuh" + +namespace deepmd_dpa4c { + +constexpr int kBlockThreads = 256; +constexpr int kBlockWarps = kBlockThreads / kWarpSize; +/// Items of the channel-contiguous amplitude order whose radial table rows a +/// lane loads together, ahead of their evaluation (panel_radial). +constexpr int kAmplitudeBatch = 4; + +/// Shared memory that the smaller layout of an edge scan may hold, so that +/// every supported device gives it a block: the 64 KB that a block of compute +/// capability 7.5 may opt in to, the least of the supported devices (96 KB on +/// 7.0, 99 KB or more from 8.0 on). +constexpr size_t kPanelSharedLimit = 64 * 1024; + +/// The geometry of the panels of an edge scan: the edges of a panel, the tile +/// of edges and channels of a lane, and the resident blocks per +/// multiprocessor for which the scan is compiled, zero leaving its register +/// budget to the compiler. +template +struct PanelShape { + static constexpr int Edges = EdgeCount; + static constexpr int ThreadEdges = TileEdges; + static constexpr int ThreadChannels = TileChannels; + static constexpr int MinBlocks = Blocks; +}; + +/// The panel geometry of the forward and the backward (``Reverse``) edge scan +/// of every scalar width and angular degree. A lane tile of 4 x 4 issues half +/// the shared-memory reads per fused multiply-add of a tile of 2 x 4, and a +/// panel of 64 edges reads the streamed weights of the products half as often +/// per edge as a panel of 32, so a scan takes the widest tile and panel that +/// keep two blocks per multiprocessor. At 64 channels that holds for both +/// scans of degree two and for the forward of degree three; the backward from +/// degree three, whose register tile and per-edge state grow with the degree, +/// and both scans of degree four keep panels of 32 edges. At 128 channels a +/// panel holds 32 edges. The compiler gives a backward more registers than two +/// blocks leave, and the budget of two blocks, at the cost of a small spill, +/// runs it much faster than one block at the compiler's own count, so every +/// backward is compiled for two blocks; the forward scans fit two blocks on +/// the compiler's count. +template +using ScanShape = PanelShape; +template +struct BlockPanel; +template +struct BlockPanel<8, Lmax, Reverse> : ScanShape<64, 1, 2, Reverse> {}; +template +struct BlockPanel<16, Lmax, Reverse> : ScanShape<64, 1, 4, Reverse> {}; +template +struct BlockPanel<32, Lmax, Reverse> : ScanShape<64, 2, 4, Reverse> {}; +template +struct BlockPanel<64, Lmax, Reverse> : ScanShape<64, 4, 4, Reverse> {}; +template <> +struct BlockPanel<64, 3, true> : ScanShape<32, 2, 4, true> {}; +template +struct BlockPanel<64, 4, Reverse> : ScanShape<32, 2, 4, Reverse> {}; +template +struct BlockPanel<128, Lmax, Reverse> : ScanShape<32, 4, 4, Reverse> {}; + +/// The layout of the panels of one edge scan: the profile of the block, the +/// direction of the scan, and its panel geometry (BlockPanel). ``Reverse`` +/// marks the backward, which reads every entry of a row as the edge the row +/// emits. +template +struct PanelLayout { + static constexpr int Channels = ChannelCount; + static constexpr int Lmax = Degree; + static constexpr bool HasSpin = Spin; + static constexpr bool HasModes = Modes; + static constexpr bool Reverse = Backward; + using B = BlockProfile; + using S = BlockPanel; + static constexpr int Edges = S::Edges; + static_assert(Edges == kWarpSize || Edges == 2 * kWarpSize, + "a panel holds one or two warps of edges"); + static constexpr int TE = S::ThreadEdges; + static constexpr int TC = S::ThreadChannels; + static_assert(TC <= 4 && B::P::C2 % TC == 0, + "a channel tile lies inside or outside every degree of two or " + "more channels"); + static constexpr int ChannelTiles = Channels / TC; + static constexpr int EdgeTiles = Edges / TE; + static_assert(ChannelTiles * EdgeTiles == kBlockThreads, + "the tiles of a panel cover the lanes of a block"); + /// A warp covers 8 edge tiles of 4 channel tiles each, so that each warp + /// reads a slice of the weights of a product rather than all of them; the + /// channel tiles of an edge are dealt in groups of four to + /// ``ChannelGroups`` warps (see panel_tile for the lanes of a warp). + static constexpr int WarpChannelTiles = 4; + static constexpr int WarpEdgeTiles = kWarpSize / WarpChannelTiles; + static_assert(ChannelTiles % WarpChannelTiles == 0, + "the channel tiles of an edge fill whole warps"); + static constexpr int ChannelGroups = ChannelTiles / WarpChannelTiles; + /// Row stride of the feature-major operand, padded to a 16-byte multiple. + static constexpr int Stride = Edges + 4; + static constexpr int BasisWidth = (Lmax + 1) * (Lmax + 1); +}; + +/// The tile of a lane in a panel: its channel group, whether it leads the +/// lanes of its warp that share its edges, and the first edge and channel of +/// its tile. +struct PanelTile { + int group; + bool leader; + int e0; + int c0; +}; + +/// Lane ``l`` of a warp holds the channel tile (l / 2) % 4 and the edge tile +/// 2 (l / 8) + l % 2 of the warp: every quarter-warp holds two edge tiles and +/// all four channel tiles, and the lanes that read one weight word of a +/// product are adjacent in pairs. On sm_120 this order needs fewer shared +/// wavefronts per contraction step than one with the channel tile as the +/// fastest lane index, by about a third more fused multiply-adds per cycle at +/// the tiles of BlockPanel. The lanes of an edge tile are l, l ^ 2, l ^ 4 and +/// l ^ 6, of which the one of channel tile zero leads. +template +__device__ __forceinline__ PanelTile panel_tile() { + const int warp = threadIdx.x / kWarpSize; + const int lane = threadIdx.x % kWarpSize; + const int group = warp % L::ChannelGroups; + const int warp_channel_tile = lane / 2 % L::WarpChannelTiles; + const int channel_tile = group * L::WarpChannelTiles + warp_channel_tile; + const int edge_tile = + (warp / L::ChannelGroups) * L::WarpEdgeTiles + 2 * (lane / 8) + lane % 2; + return {group, warp_channel_tile == 0, edge_tile * L::TE, + channel_tile * L::TC}; +} + +/// Edge and channel of one item of the channel-contiguous order of +/// panel_radial. +struct RadialItem { + int edge; + int channel; +}; + +/// The channel-contiguous order of the amplitudes of a panel: tiles of eight +/// channels, an octet, by four edges, a quad, one item of a tile per lane. The +/// warps of a block form a grid of WarpOctets by WarpQuads, and warp (o, q) +/// holds the tiles of the octets o + WarpOctets a and the quads q + WarpQuads +/// b, item b + QuadItems a of each lane. Every item of a lane then lies at a +/// fixed offset from the first, so its addresses cost no registers of their +/// own. +template +struct RadialPanel { + static constexpr int Octets = L::Channels / 8; + static constexpr int Quads = L::Edges / 4; + static constexpr int WarpOctets = Octets < kBlockWarps ? Octets : kBlockWarps; + static constexpr int WarpQuads = kBlockWarps / WarpOctets; + static_assert(L::Channels % 8 == 0 && Octets % WarpOctets == 0 && + Quads % WarpQuads == 0, + "the octets and edge quads of a panel tile its warps evenly"); + static constexpr int OctetItems = Octets / WarpOctets; + static constexpr int QuadItems = Quads / WarpQuads; + static constexpr int Items = OctetItems * QuadItems; + + __device__ static __forceinline__ RadialItem item(int n) { + const int warp = threadIdx.x / kWarpSize; + const int lane = threadIdx.x % kWarpSize; + const int octet = warp % WarpOctets + WarpOctets * (n / QuadItems); + const int quad = warp / WarpOctets + WarpQuads * (n % QuadItems); + return {4 * quad + lane / 8, 8 * octet + lane % 8}; + } +}; + +// === Small dense helpers === + +__device__ __forceinline__ float soft_saturate(float value, float knee) { + const float ratio = value / knee; + return value * rsqrtf(1.0f + ratio * ratio); +} + +/// Derivative of `soft_saturate`, (1 + (x / k)^2)^(-3/2). +__device__ __forceinline__ float soft_saturate_slope(float value, float knee) { + const float ratio = value / knee; + const float inverse = rsqrtf(1.0f + ratio * ratio); + return inverse * inverse * inverse; +} + +__device__ __forceinline__ float block_silu(float value) { + return value / (1.0f + __expf(-value)); +} + +__device__ __forceinline__ float block_silu_slope(float value) { + const float gate = 1.0f / (1.0f + __expf(-value)); + return gate * (1.0f + value * (1.0f - gate)); +} + +__device__ __forceinline__ float softplus(float value) { + return value > 0.0f ? value + log1pf(__expf(-value)) : log1pf(__expf(value)); +} + +/// Invoke ``body`` with the rank of the radial mode residual as a compile-time +/// constant, zero for a profile without modes and otherwise one of the ranks +/// 2, 4 and 8 that the operator admits. The loops over the modes then unroll, +/// so the loads of every channel of a tile issue ahead of its sums. +template +__device__ __forceinline__ void with_mode_rank(int rank, const Body& body) { + if constexpr (!HasModes) { + body(std::integral_constant{}); + } else if (rank == 2) { + body(std::integral_constant{}); + } else if (rank == 4) { + body(std::integral_constant{}); + } else { + body(std::integral_constant{}); + } +} + +template +__device__ __forceinline__ void load_floats(const float* source, + float (&target)[Count]) { + if constexpr (Count % 4 == 0) { +#pragma unroll + for (int i = 0; i < Count; i += 4) { + const float4 value = *reinterpret_cast(source + i); + target[i] = value.x; + target[i + 1] = value.y; + target[i + 2] = value.z; + target[i + 3] = value.w; + } + } else if constexpr (Count == 2) { + const float2 value = *reinterpret_cast(source); + target[0] = value.x; + target[1] = value.y; + } else { +#pragma unroll + for (int i = 0; i < Count; ++i) { + target[i] = source[i]; + } + } +} + +template +__device__ __forceinline__ void load_floats_cached(const float* source, + float (&target)[Count]) { + if constexpr (Count % 4 == 0) { +#pragma unroll + for (int i = 0; i < Count; i += 4) { + const float4 value = __ldg(reinterpret_cast(source + i)); + target[i] = value.x; + target[i + 1] = value.y; + target[i + 2] = value.z; + target[i + 3] = value.w; + } + } else if constexpr (Count == 2) { + const float2 value = __ldg(reinterpret_cast(source)); + target[0] = value.x; + target[1] = value.y; + } else { +#pragma unroll + for (int i = 0; i < Count; ++i) { + target[i] = __ldg(source + i); + } + } +} + +/// Copy 16 bytes from global into shared memory. In an image compiled for +/// compute capability 8.0 or later the copy is asynchronous and completes at +/// the matching ``copy_async_wait``; an image compiled for compute +/// capability 7.x copies at once, which the barriers that follow the wait +/// order the same way. +__device__ __forceinline__ void copy_async16(float* dst, const float* src) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + const unsigned address = static_cast(__cvta_generic_to_shared(dst)); + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"(address), + "l"(src)); +#else + *reinterpret_cast(dst) = __ldg(reinterpret_cast(src)); +#endif +} + +/// Copy 4 bytes from global into shared memory, asynchronously in an image +/// compiled for compute capability 8.0 or later, as copy_async16 does. +__device__ __forceinline__ void copy_async4(float* dst, const float* src) { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + const unsigned address = static_cast(__cvta_generic_to_shared(dst)); + asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"(address), + "l"(src)); +#else + *dst = __ldg(src); +#endif +} + +__device__ __forceinline__ void copy_async_commit() { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + asm volatile("cp.async.commit_group;\n" ::); +#endif +} + +__device__ __forceinline__ void copy_async_wait_all() { +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + asm volatile("cp.async.wait_group 0;\n" ::); +#endif +} + +/// Whether the copies above are asynchronous: in an image compiled for compute +/// capability 8.0 or later. It describes device code; host code sees false. +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 +constexpr bool kAsyncCopy = true; +#else +constexpr bool kAsyncCopy = false; +#endif + +/// Floats of a weight chunk that a streamed product stages at a time: rows of +/// 1024 floats, sixteen rows of 64 columns. +constexpr int kWeightChunkFloats = 1024; + +template +constexpr int weight_chunk_rows() { + return kWeightChunkFloats / Columns; +} + +/// Floats of the staging buffer of a streamed product of ``Columns`` columns: +/// two chunks. +template +constexpr int weight_stage_floats() { + return 2 * weight_chunk_rows() * Columns; +} + +/// Chunks of a streamed product of depth ``Depth`` and ``Columns`` columns. +template +constexpr int weight_chunks() { + return (Depth + weight_chunk_rows() - 1) / + weight_chunk_rows(); +} + +/// Whether the chunks of a streamed product of ``Columns`` columns move through +/// the registers of the threads (panel_product), whose loads then hide behind +/// the contraction of the chunk before. The chunks of 64 columns do. A chunk of +/// 8 rows of 128 columns contracts too briefly to hide its load behind it and +/// is copied asynchronously where the device copies asynchronously +/// (kAsyncCopy); elsewhere a copy would load and store at once, and the +/// registers carry the chunks of 128 columns as well. +template +constexpr bool stages_through_registers() { + return Columns == 64 || (Columns == 128 && !kAsyncCopy); +} + +/// acc[i][j] += sum over k < Depth of operand[k][e0 + i] * weight[k][c0 + j], +/// the operand feature-major in shared memory with row stride ``Stride`` and +/// the weight input-major with ``Columns`` columns. A ``Resident`` weight is in +/// shared memory. Otherwise it is in global memory and streams through +/// ``stage`` (weight_stage_floats) in chunks of weight_chunk_rows, which the +/// threads of the block move cooperatively one chunk ahead of the rows the +/// product reads, so that the latency of the moves hides behind the +/// contraction; every thread of the block then takes part. A chunk moves +/// through the registers of the threads where stages_through_registers holds, +/// one vector each, loaded before the contraction of the chunk before and +/// stored after it, so that the load hides behind that contraction and the +/// contraction reads shared memory undisturbed by copies into it; any other +/// chunk is copied with copy_async16. +/// The chunks take the two buffers of the stage in turn from buffer ``First`` +/// on. The first chunk is already on its way when ``filled``, and the stage is +/// otherwise free on entry; given ``next``, the weight of a streamed product of +/// the same columns and at least one chunk of depth that follows, the last +/// chunk of the product moves the first chunk of ``next`` into the buffer after +/// its own, so that the moves of consecutive products overlap their +/// contractions. A full chunk is contracted in a loop of its compile-time +/// length, whose loads the compiler issues ahead of their products. The +/// contraction runs in ascending k with one fused multiply-add per term. +template +__device__ __forceinline__ void panel_product(const float* operand, + const float* weight, + float* stage, + int e0, + int c0, + float (&acc)[TE][TC], + bool filled = false, + const float* next = nullptr) { + const auto step = [&](const float* row, int k) { + float a[TE]; + float b[TC]; + load_floats(operand + k * Stride + e0, a); + load_floats(row + c0, b); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] = fmaf(a[i], b[j], acc[i][j]); + } + } + }; + const auto contract = [&](const float* rows, int first, int count) { +#pragma unroll 4 + for (int k = 0; k < count; ++k) { + step(rows + k * Columns, first + k); + } + }; + if constexpr (Resident) { + contract(weight, 0, Depth); + } else if constexpr (stages_through_registers()) { + constexpr int kWeightChunk = weight_chunk_rows(); + constexpr int Chunks = weight_chunks(); + static_assert(kWeightChunk * Columns == 4 * kBlockThreads, + "a chunk moves as one vector of every thread"); + const auto buffer = [&](int chunk) { + return stage + (First + chunk) % 2 * kWeightChunk * Columns; + }; + const int index = threadIdx.x * 4; + const auto load = [&](const float* source, int floats) { + return index < floats + ? __ldg(reinterpret_cast(source + index)) + : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + }; + const auto rows_of = [&](int chunk) { + return min(kWeightChunk, Depth - chunk * kWeightChunk) * Columns; + }; + if (!filled) { + *reinterpret_cast(buffer(0) + index) = load(weight, rows_of(0)); + } + for (int chunk = 0; chunk < Chunks; ++chunk) { + // The chunk is in its buffer, and every thread has left the chunk + // before, whose buffer the next chunk takes. + __syncthreads(); + const bool ahead = chunk + 1 < Chunks || next != nullptr; + const float4 moved = + chunk + 1 < Chunks + ? load(weight + (chunk + 1) * kWeightChunk * Columns, + rows_of(chunk + 1)) + : (next != nullptr ? load(next, kWeightChunk * Columns) + : make_float4(0.0f, 0.0f, 0.0f, 0.0f)); + const float* rows = buffer(chunk); + const int first = chunk * kWeightChunk; + if (Depth - first >= kWeightChunk) { +#pragma unroll + for (int k = 0; k < kWeightChunk; ++k) { + step(rows + k * Columns, first + k); + } + } else { + contract(rows, first, Depth - first); + } + if (ahead) { + *reinterpret_cast(buffer(chunk + 1) + index) = moved; + } + } + } else { + constexpr int kWeightChunk = weight_chunk_rows(); + constexpr int Chunks = weight_chunks(); + const auto buffer = [&](int chunk) { + return stage + (First + chunk) % 2 * kWeightChunk * Columns; + }; + const auto copy = [&](float* target, const float* source, int floats) { + for (int index = threadIdx.x * 4; index < floats; + index += kBlockThreads * 4) { + copy_async16(target + index, source + index); + } + copy_async_commit(); + }; + const auto fill = [&](int chunk) { + copy(buffer(chunk), weight + chunk * kWeightChunk * Columns, + min(kWeightChunk, Depth - chunk * kWeightChunk) * Columns); + }; + if (!filled) { + fill(0); + } + for (int chunk = 0; chunk < Chunks; ++chunk) { + // The chunk has landed, and every thread has left the chunk before, + // whose buffer the next copy reuses. + copy_async_wait_all(); + __syncthreads(); + if (chunk + 1 < Chunks) { + fill(chunk + 1); + } else if (next != nullptr) { + copy(buffer(Chunks), next, kWeightChunk * Columns); + } + const float* rows = buffer(chunk); + const int first = chunk * kWeightChunk; + if (Depth - first >= kWeightChunk) { +#pragma unroll + for (int k = 0; k < kWeightChunk; ++k) { + step(rows + k * Columns, first + k); + } + } else { + contract(rows, first, Depth - first); + } + } + } +} + +/// Real Cartesian harmonics through ``Lmax`` in the packed layout of +/// ``build_angular_basis``. +template +__device__ __forceinline__ void fill_block_basis(const EdgeGeometry& geometry, + float* basis) { + float low[9]; + fill_angular_basis(geometry, low); +#pragma unroll + for (int index = 0; index < 9; ++index) { + basis[index] = low[index]; + } + if constexpr (Lmax >= 3) { +#pragma unroll + for (int index = 0; index < (Lmax >= 4 ? 16 : 7); ++index) { + basis[9 + index] = high_basis_value(geometry, index); + } + } +} + +/// Unit-direction geometry of one edge vector for the basis helpers. +__device__ __forceinline__ EdgeGeometry block_geometry(float x, + float y, + float z, + float eps) { + EdgeGeometry geometry; + const float square = x * x + y * y + z * z + eps * eps; + geometry.inverse_radius = rsqrtf(square); + geometry.radius = square * geometry.inverse_radius; + geometry.ux = x * geometry.inverse_radius; + geometry.uy = y * geometry.inverse_radius; + geometry.uz = z * geometry.inverse_radius; + geometry.seen = geometry.radius; + geometry.envelope = 0.0f; + geometry.source_type = 0; + geometry.source = 0; + return geometry; +} + +/// Coordinate of the moment layout of one degree, component and channel. +template +__device__ __forceinline__ int moment_coordinate(int degree, + int component, + int channel) { + return B::moment_offset(degree) + component * B::width_of(degree) + channel; +} + +/// Degree, component and channel of an angular moment coordinate. +template +__device__ __forceinline__ void decode_angular(int coordinate, + int& degree, + int& component, + int& channel) { + degree = Lmax; +#pragma unroll + for (int l = Lmax; l >= 1; --l) { + if (coordinate >= B::moment_offset(l)) { + degree = l; + break; + } + } + const int offset = coordinate - B::moment_offset(degree); + component = offset / B::width_of(degree); + channel = offset % B::width_of(degree); +} + +// === Node maps === +// +// The node maps are one dense layer over the saturated invariants of every +// node, pre = sat(D) W + b, whose columns hold the gate and the value of the +// SwiGLU state encoder, the neighbor term of the edge hidden layer and the +// null-mass logits (BlockLayout.node_weight of attention.py). The layer runs on +// the GEMM tiles of simt_gemm.cuh, one CTA per column tile of 32 nodes; the +// CTA of the first column tile, which holds the gate and the value, also +// finishes the state encoder and the keys of its nodes. The backward +// recomputes the first column tile, forms the cotangent of every column of the +// layer and the moment gradient of the keys there, and contracts the +// cotangent with the transpose of the layer in a second GEMM, whose epilogue +// applies the slope of the saturation. + +/// GEMM tile of the node maps: 32 nodes by 64 columns, 4 x 4 accumulators per +/// lane over 32-deep slices, the small tile of the fitting network. +using NodeTile = deepmd_gemm::GemmTile<32, 64, 4, 4, 32, 2, 2, 3>; +static_assert(NodeTile::cols >= 2 * kBlockStateHidden, + "the first column tile holds the gate and the value"); + +/// The A operand of the node input layer, the invariants of a run saturated +/// while they are staged. +template +struct SaturatedStager : deepmd_gemm::InputStager { + using Base = deepmd_gemm::InputStager; + float knee; + + __device__ SaturatedStager( + const float* descriptor, long row0, long nodes, int width, float knee_) + : Base(descriptor, row0, nodes, width), knee(knee_) {} + + __device__ __forceinline__ void commit( + float (*a)[NodeTile::rows + deepmd_gemm::kSkew]) { +#pragma unroll + for (auto& value : this->v) { + if constexpr (Vector) { + value = make_float4( + soft_saturate(value.x, knee), soft_saturate(value.y, knee), + soft_saturate(value.z, knee), soft_saturate(value.w, knee)); + } else { + value = soft_saturate(value, knee); + } + } + Base::commit(a); + } +}; + +/// The accumulators of the node input layer of the tile of a CTA, pre - b, +/// for the column tile at ``tile.col0``. +template +__device__ __forceinline__ void node_input_layer( + const BlockArguments& block, + const deepmd_gemm::TileIndex& tile, + const deepmd_gemm::LaneOrigin& origin, + deepmd_gemm::GemmStorage& smem, + deepmd_gemm::Accumulators& acc) { + using P = Profile; + using B = BlockProfile; + SaturatedStager a( + block.descriptor, tile.row0, block.edges.node_count, P::OutputWidth, + __ldg(block.record + 1)); + deepmd_gemm::WeightStager b(block.record + B::NodeWeight, tile.col0, + P::OutputWidth, B::NodeWidth); + deepmd_gemm::gemm_mainloop(smem, a, b, P::OutputWidth, origin, acc); +} + +/// The gate and the value of the state encoder of the nodes of a first column +/// tile, pre = acc + b, into ``gate`` (rows, 2 StateHidden); the stores +/// precede a barrier. +template +__device__ __forceinline__ void store_gate( + const float* record, + const deepmd_gemm::LaneOrigin& origin, + const deepmd_gemm::Accumulators& acc, + float (*gate)[B::NodeHidden]) { +#pragma unroll + for (int i = 0; i < NodeTile::tm; ++i) { + const int r = deepmd_gemm::accumulator_row(origin, i); +#pragma unroll + for (int g = 0; g < NodeTile::tn / 4; ++g) { + const int n = deepmd_gemm::accumulator_col(origin, g); + if (n < B::NodeHidden) { +#pragma unroll + for (int j = 0; j < 4; ++j) { + gate[r][n + j] = + acc[i][4 * g + j] + __ldg(record + B::NodeBias + n + j); + } + } + } + } +} + +/// The node maps of the nodes of one tile of the run: the neighbor term of the +/// edge hidden layer and the null-mass logits from the column tile of the CTA, +/// and, in the CTA of the first column tile, the encoded state, the saturated +/// keys of the moments of block k - 1 and the divisor columns of the +/// descriptor, which every further block carries. +template +__global__ __launch_bounds__( + NodeTile::threads, + NodeTile::min_blocks) void block_maps_kernel(BlockArguments block) { + using P = Profile; + using B = BlockProfile; + const Arguments& args = block.edges; + const float* record = block.record; + __shared__ __align__(16) deepmd_gemm::GemmStorage smem; + const deepmd_gemm::LaneOrigin origin = deepmd_gemm::lane_origin(); + const deepmd_gemm::TileIndex tile = + deepmd_gemm::tile_index(B::NodeWidth); + deepmd_gemm::Accumulators acc; + node_input_layer(block, tile, origin, smem, acc); + + // === Hidden-layer term and null-mass logits === +#pragma unroll + for (int i = 0; i < NodeTile::tm; ++i) { + const long row = + tile.row0 + deepmd_gemm::accumulator_row(origin, i); +#pragma unroll + for (int g = 0; g < NodeTile::tn / 4; ++g) { + const int n = + tile.col0 + deepmd_gemm::accumulator_col(origin, g); + if (row >= args.node_count || n < B::NodeHidden || + n >= B::NodeNull + B::Heads) { + continue; + } + const long node = args.node_begin + row; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float value = + acc[i][4 * g + j] + __ldg(record + B::NodeBias + n + j); + if (n + j < B::NodeNull) { + block.sources[node * B::SourceWidth + B::SourceHidden + n + j - + B::NodeHidden] = value; + } else if (n + j < B::NodeNull + B::Heads) { + block.centers[node * B::Heads + n + j - B::NodeNull] = value; + } + } + } + } + if (tile.col0 != 0) { + return; + } + + // === Encoded state === + auto* gate = reinterpret_cast(&smem.a[0][0][0]); + store_gate(record, origin, acc, gate); + __syncthreads(); + const int count = static_cast( + min(static_cast(NodeTile::rows), args.node_count - tile.row0)); + for (int index = threadIdx.x; index < count * Channels; + index += NodeTile::threads) { + const int r = index / Channels; + const int c = index % Channels; + float state = 0.0f; +#pragma unroll + for (int q = 0; q < B::StateHidden; ++q) { + state = fmaf(block_silu(gate[r][q]) * gate[r][B::StateHidden + q], + __ldg(record + B::StateOutput + q * Channels + c), state); + } + const long node = args.node_begin + tile.row0 + r; + block.sources[node * B::SourceWidth + B::SourceState + c] = state; + } + // === Divisor columns === + for (int index = threadIdx.x; index < count * 2; index += NodeTile::threads) { + const long row = tile.row0 + index / 2; + block.divisors[(args.node_begin + row) * 2 + index % 2] = + block.descriptor[row * P::OutputWidth + P::OutputDivisor + index % 2]; + } + // === Saturated keys of the moments of block k - 1 === + const float key_knee = __ldg(record + 2); + for (int index = threadIdx.x; index < count * Lmax * B::Heads; + index += NodeTile::threads) { + const int r = index / (Lmax * B::Heads); + const int degree = 1 + (index / B::Heads) % Lmax; + const int h = index % B::Heads; + const long node = args.node_begin + tile.row0 + r; + const float* moments = block.previous_state + node * P::StateWidth; + const float* projection = record + B::key_offset(degree); + const int width = B::width_of(degree); + float key[9]; + float norm = 0.0f; + for (int m = 0; m < 2 * degree + 1; ++m) { + float value = 0.0f; + for (int c = 0; c < width; ++c) { + value = fmaf(moments[moment_coordinate(degree, m, c)], + __ldg(projection + c * B::Heads + h), value); + } + key[m] = value; + norm = fmaf(value, value, norm); + } + const float scale = rsqrtf(1.0f + norm / (key_knee * key_knee)); + float* keys = block.sources + node * B::SourceWidth; + for (int m = 0; m < 2 * degree + 1; ++m) { + keys[(B::harmonic_offset(degree) + m) * B::Heads + h] = key[m] * scale; + } + } +} + +/// The first half of the backward of the node maps, over the nodes of one tile +/// of the run: the cotangent of every column of the node input layer, from the +/// cotangent of the source features and of the null-mass logits, into +/// ``map_cotangent``, and the moment gradient of the keys, in the +/// node-backward layout of block k - 1. The SwiGLU state encoder pulls the +/// state cotangent back onto its gate and value, which the first column tile +/// of the layer recomputes; the hidden-layer term and the null-mass logits +/// pass theirs through. +template +__global__ __launch_bounds__( + NodeTile::threads, + NodeTile::min_blocks) void block_map_cotangent_kernel(BlockArguments + block) { + using P = Profile; + using B = BlockProfile; + const Arguments& args = block.edges; + const float* record = block.record; + __shared__ __align__(16) deepmd_gemm::GemmStorage smem; + const deepmd_gemm::LaneOrigin origin = deepmd_gemm::lane_origin(); + const deepmd_gemm::TileIndex tile = + deepmd_gemm::tile_index(NodeTile::cols); + deepmd_gemm::Accumulators acc; + node_input_layer(block, tile, origin, smem, acc); + auto* gate = reinterpret_cast(&smem.a[0][0][0]); + auto* d_product = reinterpret_cast( + &smem.a[0][0][0] + NodeTile::rows * B::NodeHidden); + store_gate(record, origin, acc, gate); + const int count = static_cast( + min(static_cast(NodeTile::rows), args.node_count - tile.row0)); + + // === Cotangent of the SwiGLU products === + for (int index = threadIdx.x; index < count * B::StateHidden; + index += NodeTile::threads) { + const int r = index / B::StateHidden; + const int q = index % B::StateHidden; + const float* gradient = + block.source_gradient + (tile.row0 + r) * B::SourceWidth; + float value = 0.0f; + for (int c = 0; c < Channels; ++c) { + value = fmaf(gradient[B::SourceState + c], + __ldg(record + B::StateOutput + q * Channels + c), value); + } + d_product[r][q] = value; + } + __syncthreads(); + + // === Cotangent of the node input layer === + for (int index = threadIdx.x; index < count * B::NodeWidth; + index += NodeTile::threads) { + const int r = index / B::NodeWidth; + const int n = index % B::NodeWidth; + const long row = tile.row0 + r; + const float* gradient = block.source_gradient + row * B::SourceWidth; + float value = 0.0f; + if (n < B::NodeHidden) { + const int q = n % B::StateHidden; + const float pre = gate[r][q]; + value = n < B::StateHidden + ? d_product[r][q] * gate[r][B::StateHidden + q] * + block_silu_slope(pre) + : d_product[r][q] * block_silu(pre); + } else if (n < B::NodeNull) { + value = gradient[B::SourceHidden + n - B::NodeHidden]; + } else if (n < B::NodeNull + B::Heads) { + value = block.center_gradient[row * B::Heads + n - B::NodeNull]; + } + block.map_cotangent[row * B::NodeWidth + n] = value; + } + + // === Moment gradient of the keys === + // One warp per node. For every degree the lanes form the keys of both + // heads, the cotangent of the raw keys through the saturation, and then + // the moment gradient of every coordinate of the degree, with the angular + // mass term reduced over the warp in a fixed order. + constexpr int Warps = NodeTile::threads / kWarpSize; + __shared__ float key_scratch[Warps][2][B::Heads * 9]; + const float key_knee = __ldg(record + 2); + const int warp = threadIdx.x / kWarpSize; + const int lane = threadIdx.x % kWarpSize; + for (int r = warp; r < count; r += Warps) { + const long row = tile.row0 + r; + const long node = args.node_begin + row; + const float* moments = block.previous_state + node * P::StateWidth; + const float angular_norm = moments[P::MomentWidth + 1]; + const float* gradient = block.source_gradient + row * B::SourceWidth; + float* output = block.keys_gradient + row * P::StateWidth; + float* key = key_scratch[warp][0]; + float* d_key = key_scratch[warp][1]; + // Only the angular coordinates carry a key gradient. + for (int coordinate = lane; coordinate < P::StateWidth; + coordinate += kWarpSize) { + if (coordinate < P::VectorOffset || coordinate >= B::GeometricWidth) { + output[coordinate] = 0.0f; + } + } + float mass = 0.0f; +#pragma unroll + for (int degree = 1; degree <= Lmax; ++degree) { + const float* projection = record + B::key_offset(degree); + const int width = B::width_of(degree); + const int components = 2 * degree + 1; + // key[h][m] = sum_c X[m][c] P[c][h] + if (lane < components * B::Heads) { + const int m = lane / B::Heads; + const int h = lane % B::Heads; + float value = 0.0f; + for (int c = 0; c < width; ++c) { + value = fmaf(moments[moment_coordinate(degree, m, c)], + __ldg(projection + c * B::Heads + h), value); + } + key[h * 9 + m] = value; + } + __syncwarp(); + // k = b / s with s = sqrt(1 + |b|^2 / kappa^2), so + // db = dk / s - b (b . dk) / (kappa^2 s^3). + if (lane < components * B::Heads) { + const int m = lane / B::Heads; + const int h = lane % B::Heads; + float norm = 0.0f; + float dot = 0.0f; + for (int n = 0; n < components; ++n) { + const float value = key[h * 9 + n]; + norm = fmaf(value, value, norm); + dot = fmaf(value, + gradient[(B::harmonic_offset(degree) + n) * B::Heads + h], + dot); + } + const float inverse = rsqrtf(1.0f + norm / (key_knee * key_knee)); + const float shrink = + dot * inverse * inverse * inverse / (key_knee * key_knee); + d_key[h * 9 + m] = + gradient[(B::harmonic_offset(degree) + m) * B::Heads + h] * + inverse - + key[h * 9 + m] * shrink; + } + __syncwarp(); + for (int index = lane; index < components * width; index += kWarpSize) { + const int m = index / width; + const int c = index % width; + const int coordinate = moment_coordinate(degree, m, c); + float d_moment = 0.0f; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + d_moment = fmaf(d_key[h * 9 + m], + __ldg(projection + c * B::Heads + h), d_moment); + } + // The node-backward layout holds the gradient of the raw sums, the + // normalized one times the norm. + output[coordinate] = d_moment * angular_norm; + mass = fmaf(d_moment, moments[coordinate], mass); + } + __syncwarp(); + } + // A normalized moment X = rho n depends on the angular mass through n, + // dn / dmass = -n^3 / 2. + mass = warp_sum(mass); + if (lane == 0) { + output[P::MomentWidth + 1] = -0.5f * angular_norm * angular_norm * mass; + } + } +} + +/// The second half of the backward of the node maps, over one tile of the +/// invariants of the run: their cotangent, the cotangent of the node input +/// layer contracted with the transpose of the layer, times the slope of the +/// saturation, into ``descriptor_gradient``, which may take the place of +/// ``descriptor``. +template +__global__ __launch_bounds__( + NodeTile::threads, + NodeTile::min_blocks) void block_map_input_kernel(BlockArguments block) { + using P = Profile; + using B = BlockProfile; + const Arguments& args = block.edges; + __shared__ __align__(16) deepmd_gemm::GemmStorage smem; + const deepmd_gemm::LaneOrigin origin = deepmd_gemm::lane_origin(); + const deepmd_gemm::TileIndex tile = + deepmd_gemm::tile_index(P::OutputWidth); + deepmd_gemm::Accumulators acc; + { + deepmd_gemm::InputStager a(block.map_cotangent, tile.row0, + args.node_count, B::NodeWidth); + deepmd_gemm::WeightTransposeStager b( + block.record + B::NodeWeight, tile.col0, B::NodeWidth, P::OutputWidth); + deepmd_gemm::gemm_mainloop(smem, a, b, B::NodeWidth, origin, acc); + } + const float knee = __ldg(block.record + 1); +#pragma unroll + for (int i = 0; i < NodeTile::tm; ++i) { + const long row = + tile.row0 + deepmd_gemm::accumulator_row(origin, i); +#pragma unroll + for (int g = 0; g < NodeTile::tn / 4; ++g) { + const int k = + tile.col0 + deepmd_gemm::accumulator_col(origin, g); +#pragma unroll + for (int j = 0; j < 4; ++j) { + if (row < args.node_count && k + j < P::OutputWidth) { + const long index = row * P::OutputWidth + k + j; + const float invariant = block.descriptor[index]; + block.descriptor_gradient[index] = + acc[i][4 * g + j] * soft_saturate_slope(invariant, knee); + } + } + } + } +} + +// === Node part of the backward === + +/// From the node-backward output at the moments of block k, the destination +/// cotangents that the edges of block k read, the cotangent of the null-mass +/// logits, and the moment gradient carried back to the first block. One warp +/// owns one node. +template +__global__ __launch_bounds__(kBlockThreads) void block_cotangent_kernel( + BlockArguments block) { + using P = Profile; + using B = BlockProfile; + const Arguments& args = block.edges; + const float* record = block.record; + const int lane = threadIdx.x % kWarpSize; + const long row = static_cast(blockIdx.x) * (kBlockThreads / kWarpSize) + + threadIdx.x / kWarpSize; + if (row >= args.node_count) { + return; + } + const long node = args.node_begin + row; + const float* gradient = block.moment_gradient + row * P::StateWidth; + const float angular_norm = + block.first_state[node * P::StateWidth + P::MomentWidth + 1]; + const float* transport = block.transport + row * B::TransportWidth; + float* cotangents = block.cotangents + node * B::CotangentWidth; + float* carried = block.carried + node * P::StateWidth; + + // The transported keys enter the angular moments after the division, so the + // mass gradient of the node backward, formed against the whole moment, + // overcounts their share by -n^2/2 d.T, which the correction restores. + float correction = 0.0f; + for (int coordinate = P::VectorOffset + lane; coordinate < B::GeometricWidth; + coordinate += kWarpSize) { + int degree, component, channel; + decode_angular(coordinate, degree, component, channel); + const float* output = record + B::output_offset(degree); + const int harmonic = B::harmonic_offset(degree) + component; + float transported = 0.0f; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + transported = + fmaf(transport[harmonic * B::Heads + h], + __ldg(output + h * B::width_of(degree) + channel), transported); + } + correction = fmaf(gradient[coordinate], transported, correction); + } + correction = 0.5f * angular_norm * warp_sum(correction); + + for (int coordinate = lane; coordinate < B::GeometricWidth; + coordinate += kWarpSize) { + cotangents[coordinate] = gradient[coordinate]; + } + // dE/dT = d / n for an angular coordinate, and T = (R / den) O. + float null_gradient[B::Heads] = {}; + for (int q = lane; q < B::KeyWidth; q += kWarpSize) { + const int harmonic = q / B::Heads; + const int h = q % B::Heads; + int degree = 1; + while (B::harmonic_offset(degree + 1) <= harmonic && degree < Lmax) { + ++degree; + } + const int component = harmonic - B::harmonic_offset(degree); + const float* output = record + B::output_offset(degree); + float value = 0.0f; + for (int c = 0; c < B::width_of(degree); ++c) { + value = fmaf(gradient[moment_coordinate(degree, component, c)], + __ldg(output + h * B::width_of(degree) + c), value); + } + const float denominator = transport[B::KeyWidth + h]; + const float d_transport = value / (angular_norm * denominator); + cotangents[B::CotangentTransport + q] = d_transport; +#pragma unroll + for (int head = 0; head < B::Heads; ++head) { + if (head == h) { + null_gradient[head] -= d_transport * transport[q]; + } + } + } +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + null_gradient[h] = warp_sum(null_gradient[h]); + } + if (lane < B::Heads) { + const float mass_gradient = null_gradient[lane]; + cotangents[B::CotangentMass + lane] = mass_gradient; + const float logit = block.centers[node * B::Heads + lane]; + block.center_gradient[row * B::Heads + lane] = + mass_gradient / (1.0f + __expf(-logit)); + } + for (int coordinate = lane; coordinate < P::StateWidth; + coordinate += kWarpSize) { + const float value = gradient[coordinate] + + (coordinate == P::MomentWidth + 1 ? correction : 0.0f); + carried[coordinate] = + block.accumulate_carried ? carried[coordinate] + value : value; + } +} + +// === Edge stages === + +/// The rows of a block of an edge scan -- destination rows in the forward, +/// source rows in the backward -- and the positions of their edges in the +/// panels of the block: row ``r`` of the block is row ``row[r]`` of the run, +/// whose edges, from ``begin[r]`` in the edge arrays on, take the positions +/// from ``offset[r]`` to ``offset[r + 1]``. The rows of a block are either +/// consecutive rows of the run, whose edges are then contiguous, or +/// consecutive entries of the row list of the launch +/// (BlockArguments::scan_rows), each row with edges of its own. Its +/// alignment, a whole cycle of the shared-memory banks, leaves the banks of +/// the panel arrays of a scan, which follow it, where they would lie without +/// it. +struct __align__(128) ScanRows { + int count; + long row[kBlockRows]; + long begin[kBlockRows]; + long offset[kBlockRows + 1]; + + /// Edges of the rows of the block. + __device__ __forceinline__ long edges() const { return offset[count]; } + + /// The row of the block that holds the edge at ``position``. + __device__ __forceinline__ int row_of(long position) const { + int r = 0; + while (r + 1 < count && offset[r + 1] <= position) { + ++r; + } + return r; + } +}; + +/// The destination rows per block that minimize the time of an edge scan of +/// panels of ``Edges`` entries over ``nodes`` rows of ``entries`` entries in +/// all, among the counts 1, 2, ..., kBlockRows of at least ``least``, the +/// fewest on a tie. ``waves`` holds the time of the waves of every count +/// (scan_waves). A block of ``r`` rows of ``d`` entries on average scans +/// ``r d / Edges`` panels and, on average, half a panel more: the part of its +/// last panel that its rows leave empty. The time is evaluated in integers, so +/// that the host and the device choose alike. A larger count takes no more +/// waves, of more panels each, so it wins only at smaller degrees: the choice +/// never takes fewer rows for fewer entries. +template +__host__ __device__ inline int scan_block_rows(const ScanWaves& waves, + long nodes, + long entries, + int least) { + int fastest_rows = least; + long fastest = -1; + for (int choice = 0, rows = 1; choice < kBlockRowCounts; + ++choice, rows *= 2) { + if (rows < least) { + continue; + } + // The panels of a block in units of 1 / (2 Edges nodes). + const long time = waves.time[choice] * (2 * rows * entries + Edges * nodes); + if (fastest < 0 || time < fastest) { + fastest = time; + fastest_rows = rows; + } + } + return fastest_rows; +} + +/// The destination rows per block of an edge scan: scan_block_rows for the +/// entries of the graph of the scan over the rows of the whole system, among +/// those for which the grid of the launch provides. A grid that provides for +/// kBlockRows rows leaves no other choice. +template +__device__ __forceinline__ int device_block_rows(const BlockArguments& block) { + if (block.grid_rows == kBlockRows) { + return kBlockRows; + } + const Arguments& args = block.edges; + // The row pointer of a run starts at the first row of the run. + const long* row_ptr = args.destination_row_ptr - args.node_begin; + return scan_block_rows(block.waves, args.system_node_count, + row_ptr[args.system_node_count] - row_ptr[0], + block.grid_rows); +} + +/// The number of rows of the block of an edge scan of ``block_rows`` rows per +/// block, zero for a block past the rows of the launch, which then retires as +/// a whole. +__device__ __forceinline__ int scan_row_count(const BlockArguments& block, + int block_rows) { + const long visited = block.scan_rows != nullptr + ? static_cast(*block.scan_row_count) + : block.edges.node_count; + const long first = static_cast(blockIdx.x) * block_rows; + return static_cast( + max(min(static_cast(block_rows), visited - first), 0L)); +} + +/// The ``count`` rows of the block of an edge scan of ``block_rows`` rows per +/// block into ``scan``, which the lanes of the first warp locate together, one +/// row each; a barrier precedes their use. +__device__ __forceinline__ void locate_scan_rows(const BlockArguments& block, + int block_rows, + int count, + ScanRows& scan) { + if (threadIdx.x >= kWarpSize) { + return; + } + const Arguments& args = block.edges; + const long first = static_cast(blockIdx.x) * block_rows; + const int lane = threadIdx.x; + long row = 0; + long begin = 0; + long length = 0; + if (lane < count) { + row = block.scan_rows != nullptr ? block.scan_rows[first + lane] + : first + lane; + begin = args.destination_row_ptr[row]; + length = args.destination_row_ptr[row + 1] - begin; + } + // The offset of a row is the sum of the lengths of the rows before it. + long offset = length; +#pragma unroll + for (int step = 1; step < kBlockRows; step *= 2) { + const long before = __shfl_up_sync(0xffffffffu, offset, step); + if (lane >= step) { + offset += before; + } + } + if (lane < count) { + scan.row[lane] = row; + scan.begin[lane] = begin; + scan.offset[lane + 1] = offset; + } + if (lane == 0) { + scan.offset[0] = 0; + scan.count = count; + } +} + +/// The row segments of a panel. Its edges are sorted by row, so the edges of +/// every row form one segment: segment ``s`` holds the edges from +/// ``first[s]`` to ``first[s + 1]`` of row ``row[s]``, and ``count`` segments +/// cover the edges of the panel. +struct PanelRows { + int count; + int first[kBlockRows + 1]; + int row[kBlockRows]; +}; + +/// Per-edge state of a panel, at the head of the shared memory of an edge +/// stage. Arrays of several values per edge are stored value-major, so that +/// the lanes of a warp, which read consecutive edges, read consecutive words. +/// The forward holds the keys of the source of every edge; the backward reads +/// the keys of its rows, the sources of all their entries, and holds the +/// entry nodes, the radial derivatives and the vectors of its edges, which the +/// forward does not read. +template +struct __align__(16) PanelEdges { + using B = typename L::B; + static constexpr int Edges = L::Edges; + static constexpr int BackwardEdges = L::Reverse ? Edges : 1; + static constexpr int ModeEdges = L::HasModes ? Edges : 1; + static constexpr int KeyRows = L::Reverse ? 1 : B::KeyWidth; + long node[BackwardEdges]; + int row[Edges]; + int pair[Edges]; + int interval[Edges]; + float coordinate[Edges]; + float envelope[Edges]; + float block_envelope[Edges]; + float envelope_slope[BackwardEdges]; + float block_slope[BackwardEdges]; + /// Slope of the length the table reads with respect to the true one: the + /// switch inside a bridging window, one elsewhere. + float seen_slope[BackwardEdges]; + long source[Edges]; + float vector[3][BackwardEdges]; + float basis[L::BasisWidth][Edges]; + __align__(16) float modes[ModeEdges][kMaxRadialModes]; + __align__(16) float mode_slopes[L::Reverse ? ModeEdges : 1][kMaxRadialModes]; + float keys[KeyRows][Edges + 1]; + float tau[B::Heads][Edges]; + float mass[B::Heads][Edges]; + PanelRows rows; +}; + +/// Bytes of the shared memory of an edge scan before its operand: the per-edge +/// state of the panel, rounded up to a whole cycle of the shared-memory banks, +/// so that the operand and every region after it start on the same banks +/// whatever the size of that state. +template +constexpr size_t panel_operand_offset() { + constexpr size_t cycle = 128; + return (sizeof(PanelEdges) + cycle - 1) / cycle * cycle; +} + +/// Find the row segments of a panel of ``Edges`` edges from the rows of its +/// edges, -1 past its last edge. The first warp of the block finds them, and +/// a barrier precedes their use. +template +__device__ __forceinline__ void find_panel_rows(const int* rows, + PanelRows& segments) { + if (threadIdx.x >= kWarpSize) { + return; + } + const int lane = threadIdx.x; + int count = 0; + int end = 0; +#pragma unroll + for (int part = 0; part < Edges / kWarpSize; ++part) { + const int e = part * kWarpSize + lane; + const int row = rows[e]; + const bool head = row >= 0 && (e == 0 || rows[e - 1] != row); + const unsigned heads = __ballot_sync(0xffffffffu, head); + if (head) { + const int s = count + __popc(heads & ((1u << lane) - 1u)); + segments.first[s] = e; + segments.row[s] = row; + } + count += __popc(heads); + end += __popc(__ballot_sync(0xffffffffu, row >= 0)); + } + if (lane == 0) { + segments.count = count; + segments.first[count] = end; + } +} + +/// Consecutive lanes that share the sums of each of ``count`` values in +/// add_row_sums: the most, up to a warp, with which the values fill no more +/// than the lanes of a block. +constexpr int row_sum_parts(int count) { + int parts = 1; + while (parts < kWarpSize && 2 * parts * count <= kBlockThreads) { + parts *= 2; + } + return parts; +} + +/// The lanes that the sums of ``count`` values in ``Parts`` take in +/// add_row_sums, rounded up to whole warps: the first lane of a call that +/// follows them. +template +constexpr int row_sum_lanes(int count) { + return (count * Parts + kWarpSize - 1) / kWarpSize * kWarpSize; +} + +/// A value of add_row_sums that is the product of one, two or three rows of +/// shared memory at every edge, from the first factor on; a missing factor is +/// null. +struct RowProduct { + const float* first; + const float* second; + const float* third; + + __device__ __forceinline__ float operator()(int e) const { + float value = first[e]; + if (second != nullptr) { + value *= second[e]; + } + if (third != nullptr) { + value *= third[e]; + } + return value; + } +}; + +/// Add to ``total[row * stride + k]`` the sum over the edges ``e`` of every +/// row of a panel of ``term(e)``, ``term = term_of(k)``, for every +/// ``k < count``. ``term_of`` forms the term of a value once, ahead of its +/// sums. Every value takes ``Parts`` consecutive lanes of a warp +/// (row_sum_parts), the lanes from ``first_lane`` of the block on (a multiple +/// of the warp width) and cyclically, so that the sums of several calls +/// without a barrier between them fall on different lanes. Part ``p`` of a +/// value sums the edges of a row whose offsets from the head of the row are +/// ``p`` modulo ``Parts``, in four interleaved partial sums that are combined +/// pairwise, and butterfly steps add the parts, so the order of every sum is +/// fixed and its dependency chains are short. The lanes of a warp read their +/// values at ``Parts`` consecutive edges, which spreads the rows of the +/// operand, whose stride is four words past a multiple of the banks, over +/// more banks. +template +__device__ __forceinline__ void add_row_sums(const PanelRows& segments, + int count, + const TermOf& term_of, + float* total, + int stride, + int first_lane = 0) { + static_assert(Parts >= 1 && Parts <= kWarpSize && kWarpSize % Parts == 0, + "the parts of a value share a warp"); + const int lane = + (static_cast(threadIdx.x) + kBlockThreads - first_lane) % + kBlockThreads; + for (int base = lane - lane % kWarpSize; base < count * Parts; + base += kBlockThreads) { + const int slot = base + lane % kWarpSize; + const int k = slot / Parts; + const int part = slot % Parts; + const bool active = k < count; + const auto term = term_of(active ? k : 0); + for (int s = 0; s < segments.count; ++s) { + const int tail = segments.first[s + 1]; + float partial[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + if (active) { + int e = segments.first[s] + part; + for (; e + 3 * Parts < tail; e += 4 * Parts) { +#pragma unroll + for (int i = 0; i < 4; ++i) { + partial[i] += term(e + i * Parts); + } + } +#pragma unroll + for (int i = 0; i < 3; ++i) { + if (e + i * Parts < tail) { + partial[i] += term(e + i * Parts); + } + } + } + float sum = (partial[0] + partial[1]) + (partial[2] + partial[3]); +#pragma unroll + for (int offset = 1; offset < Parts; offset *= 2) { + sum += __shfl_xor_sync(0xffffffffu, sum, offset); + } + if (active && part == 0) { + total[segments.row[s] * stride + k] += sum; + } + } + } +} + +/// The sum of ``value`` over the four lanes of a warp that share the edges of +/// a lane (panel_tile), which every one of them receives: a butterfly whose +/// two steps add commuted operands on partner lanes, so that all four hold +/// the same bits. +__device__ __forceinline__ float tile_sum(float value) { + value += __shfl_xor_sync(0xffffffffu, value, 2); + value += __shfl_xor_sync(0xffffffffu, value, 4); + return value; +} + +/// The sums over the channel groups of the partial sums ``partial`` of +/// ``count`` values of every edge, ``(ChannelGroups, count, Edges)``, into +/// ``total``, ``(count, Edges)``, in group order. +template +__device__ __forceinline__ void close_channel_groups(const float* partial, + float* total, + int count) { + for (int index = threadIdx.x; index < count * L::Edges; + index += kBlockThreads) { + float value = 0.0f; +#pragma unroll + for (int group = 0; group < L::ChannelGroups; ++group) { + value += partial[group * count * L::Edges + index]; + } + total[index] = value; + } +} + +/// The cotangent of the fields of every edge of a panel through one edge +/// map, ``(Fields, Edges)`` into ``total``, which it replaces or, with +/// ``Add``, accumulates: the sum over the channels of the cotangents in the +/// channel rows of the operand times the field rows of the map, the leading +/// ``Fields`` rows of ``map`` (Operand, Channels), in shared memory when +/// ``Resident`` and in global memory otherwise. One thread forms the sum of +/// one field and edge, the edges of a warp consecutive, so that the lanes of a +/// warp read consecutive words of the operand and one word of the map; the +/// sum runs over the channels in four interleaved partial sums, combined +/// pairwise, so its order is fixed. +template +__device__ __forceinline__ void field_cotangent(const float* operand, + const float* map, + float* total) { + using B = typename L::B; + constexpr int Channels = L::Channels; + for (int index = threadIdx.x; index < B::Fields * L::Edges; + index += kBlockThreads) { + const float* column = operand + B::Fields * L::Stride + index % L::Edges; + const float* row = map + index / L::Edges * Channels; + float partial[4] = {0.0f, 0.0f, 0.0f, 0.0f}; +#pragma unroll 4 + for (int c = 0; c < Channels; c += 4) { + float weight[4]; + if constexpr (Resident) { + load_floats<4>(row + c, weight); + } else { + load_floats_cached<4>(row + c, weight); + } +#pragma unroll + for (int i = 0; i < 4; ++i) { + partial[i] = fmaf(column[(c + i) * L::Stride], weight[i], partial[i]); + } + } + const float sum = (partial[0] + partial[1]) + (partial[2] + partial[3]); + total[index] = Add ? total[index] + sum : sum; + } +} + +/// The degree of a non-scalar harmonic in the key layout. +template +__device__ __forceinline__ int harmonic_degree(int harmonic) { + int degree = 1; +#pragma unroll + for (int l = 2; l <= Lmax; ++l) { + degree += harmonic >= l * l - 1 ? 1 : 0; + } + return degree; +} + +/// Request the bond vectors and the source indices of the edges of the rows +/// of a block into L2 when the launch streams its bonds (see +/// `Arguments::prefetch_bonds`), dealing their lines to the threads of the +/// block, so that its panels find them in L2 as the rows of the first-block +/// scans do (prefetch_row_bonds). +template +__device__ __forceinline__ void prefetch_block_bonds(const Arguments& args, + const ScanRows& scan) { + if (args.prefetch_bonds) { + for (int r = 0; r < scan.count; ++r) { + const long begin = scan.begin[r]; + const long length = scan.offset[r + 1] - scan.offset[r]; + prefetch_lines(args.edge_vec + 3 * begin, 3 * length, + threadIdx.x, kBlockThreads); + prefetch_lines( + reinterpret_cast( + static_cast(args.edge_index) + begin), + length * static_cast(sizeof(index_t) / sizeof(float)), + threadIdx.x, kBlockThreads); + } + } +} + +/// The first-block envelope of an edge, the length its radial table reads, +/// and, for the backward, their slopes with respect to the true length. +struct BridgedEnvelope { + float envelope; + float seen; + float slope; + float seen_slope; +}; + +/// The envelope and the table length of the first block for an edge of length +/// ``radius`` between nodes of the types ``center_type`` and +/// ``source_type``, as load_geometry forms them: inside the bridging window of +/// the pair the table reads the clamped length and the envelope carries the +/// switch, and the source gate of a bridged descriptor of several blocks +/// multiplies the envelope of every edge. Under the gate the slope of the +/// switch enters through the gates of the other edges of the source, which +/// gate_closure_kernel adds, so the slope keeps c3'(r̃) w^2 alone (see +/// radial_chain). A bridged launch of the further blocks always carries the +/// source gate (evaluate_further_blocks), so the slope of a window without +/// one is not formed here. +__device__ __forceinline__ BridgedEnvelope +bridged_envelope(const Arguments& args, + float radius, + int center_type, + int source_type, + long source) { + BridgedEnvelope result{c3_envelope(radius, args.rcut), radius, + c3_envelope_derivative(radius, args.rcut), 1.0f}; + if (!args.bridged) { + return result; + } + float weight = 1.0f; + const float contact = __ldg(args.contact_radius + center_type) + + __ldg(args.contact_radius + source_type); + if (radius < args.f_outer * contact) { + const float t = window_parameter(__fdividef(radius, contact), args.f_inner, + args.inverse_f_width); + weight = bridging_switch(t); + result.seen = clamped_length(t, contact, args.f_inner, args.f_outer); + result.envelope = c3_envelope(result.seen, args.rcut) * weight; + result.slope = + c3_envelope_derivative(result.seen, args.rcut) * weight * weight; + result.seen_slope = weight; + } + if (args.source_gate != nullptr) { + const float gate = leave_one_out_gate(args.source_gate[source], weight); + result.envelope *= gate; + result.slope *= gate; + } + return result; +} + +/// Load the geometry, the harmonics and the mode profiles of the edges of a +/// panel, the node row that every edge reads, and the fields of every edge +/// into the leading rows of the operand. ``Reverse`` reads every entry as the +/// edge its row emits: the vector reversed and the entry's node as the +/// destination. The node row of an edge is, in the forward, the keys of its +/// source and, in the backward, the destination cotangents of the transport +/// and of the denominators of the entry's node, which ``gathered`` +/// (count, Edges + 1) receives value-major. One lane per edge evaluates its +/// geometry and requests the node row of the edge with copies of one word as +/// soon as it reads the entry, so that the row lands while the lane evaluates +/// the geometry; then every lane forms the fields. The panel holds the edges +/// of the rows of ``scan`` from position ``panel_begin`` on. +template +__device__ __forceinline__ void load_panel_edges( + const BlockArguments& block, + const ScanRows& scan, + long panel_begin, + PanelEdges& edges, + const float (*row_keys)[L::B::KeyWidth], + float* operand, + float* gathered) { + using B = typename L::B; + constexpr bool Reverse = L::Reverse; + constexpr int Gathered = Reverse ? B::TransportWidth : B::KeyWidth; + constexpr int GatherStride = L::Edges + 1; + const Arguments& args = block.edges; + const float* record = block.record; + const float cutoff = __ldg(record); + // === Geometry, envelopes, harmonics and mode profiles of every edge === + for (int e = threadIdx.x; e < L::Edges; e += kBlockThreads) { + const long panel_position = panel_begin + e; + const bool active = panel_position < scan.edges(); + const int row = active ? scan.row_of(panel_position) : -1; + edges.row[e] = row; + float basis[L::BasisWidth] = {}; + if (active) { + const long position = + scan.begin[row] + (panel_position - scan.offset[row]); + const long row_node = args.node_begin + scan.row[row]; + const long entry = static_cast( + static_cast(args.edge_index)[position]); + // The forward reads an edge into its destination row from its source; + // the backward reads the entry of a source row as the edge into the + // entry's node. + const long source = Reverse ? row_node : entry; + const long destination = Reverse ? entry : row_node; + const float* node_row = Reverse ? block.cotangents + + entry * B::CotangentWidth + + B::CotangentTransport + : block.sources + source * B::SourceWidth; +#pragma unroll + for (int q = 0; q < Gathered; ++q) { + copy_async4(gathered + q * GatherStride + e, node_row + q); + } + if constexpr (Reverse) { + edges.node[e] = entry; + } + edges.source[e] = source; + edges.pair[e] = + static_cast(args.atype[destination]) * args.type_count + + static_cast(args.atype[source]); + const float sign = Reverse ? -1.0f : 1.0f; + const float x = sign * args.edge_vec[position * 3 + 0]; + const float y = sign * args.edge_vec[position * 3 + 1]; + const float z = sign * args.edge_vec[position * 3 + 2]; + const EdgeGeometry geometry = block_geometry(x, y, z, args.eps); + // The envelope and the radial table of the first block, under the + // bridging window of its pair and the source gate (load_geometry); the + // envelope of the block reads the true length. + const BridgedEnvelope first = bridged_envelope( + args, geometry.radius, static_cast(args.atype[destination]), + static_cast(args.atype[source]), source); + edges.envelope[e] = first.envelope; + edges.block_envelope[e] = c3_envelope(geometry.radius, cutoff); + if constexpr (Reverse) { + edges.vector[0][e] = x; + edges.vector[1][e] = y; + edges.vector[2][e] = z; + edges.envelope_slope[e] = first.slope; + edges.seen_slope[e] = first.seen_slope; + edges.block_slope[e] = c3_envelope_derivative(geometry.radius, cutoff); + } + const TableLocation location = locate_table( + first.seen, args.table_stride, args.table_max, args.interval_count); + edges.interval[e] = location.index; + edges.coordinate[e] = location.coordinate; + fill_block_basis(geometry, basis); + with_mode_rank(args.radial_modes, [&](auto rank) { + constexpr int Modes = decltype(rank)::value; + const TableRow table = + table_row(args.table, location, args.table_width); +#pragma unroll + for (int mode = 0; mode < Modes; ++mode) { + const float2 value = evaluate_table_with_derivative( + table, L::Channels + mode, location.coordinate, false); + edges.modes[e][mode] = value.x; + if constexpr (Reverse) { + edges.mode_slopes[e][mode] = value.y; + } + } + }); + } else { +#pragma unroll + for (int q = 0; q < Gathered; ++q) { + gathered[q * GatherStride + e] = 0.0f; + } + if constexpr (Reverse) { + edges.node[e] = 0; + } + edges.source[e] = -1; + edges.pair[e] = 0; + edges.interval[e] = 0; + edges.coordinate[e] = 0.0f; + edges.envelope[e] = 0.0f; + edges.block_envelope[e] = 0.0f; + if constexpr (Reverse) { + edges.envelope_slope[e] = 0.0f; + edges.seen_slope[e] = 0.0f; + edges.block_slope[e] = 0.0f; + edges.vector[0][e] = edges.vector[1][e] = edges.vector[2][e] = 0.0f; + } + } +#pragma unroll + for (int index = 0; index < L::BasisWidth; ++index) { + edges.basis[index][e] = basis[index]; + } + } + copy_async_commit(); + copy_async_wait_all(); + __syncthreads(); + find_panel_rows(edges.row, edges.rows); + + // === Fields along the bond towards the centre === + // B_l(-u) = (-1)^l B_l(u). + for (int index = threadIdx.x; index < L::Edges * B::Fields; + index += kBlockThreads) { + const int e = index % L::Edges; + const int q = index / L::Edges; + const int degree = 1 + q / B::Heads; + const int h = q % B::Heads; + const float reflection = degree % 2 == 0 ? 1.0f : -1.0f; + float field = 0.0f; + for (int m = 0; m < 2 * degree + 1; ++m) { + const int key = (B::harmonic_offset(degree) + m) * B::Heads + h; + float value; + if constexpr (Reverse) { + value = row_keys[max(edges.row[e], 0)][key]; + } else { + value = edges.keys[key][e]; + } + field = fmaf(edges.basis[degree * degree + m][e], value, field); + } + operand[q * L::Stride + e] = reflection * field; + } +} + +/// The enveloped first-block amplitudes of the edges of a panel into the +/// channel rows of the operand, which a barrier then hands to the tiles of the +/// lanes, and, in the backward, the radial derivatives of the items of a lane +/// into ``slope``. The amplitudes are evaluated in channel-contiguous order: +/// lane ``l`` of a warp evaluates channel ``8 k + l % 8`` of edge +/// ``4 m + l / 8``, so that the eight lanes of an edge read 128 contiguous +/// bytes of its table row, its pair film and its mode mixing, which the tile +/// of a lane in the products, whose channels are contiguous per lane, would +/// read at a stride (RadialPanel). The items of a lane are evaluated in +/// batches of kAmplitudeBatch, all loads of a batch ahead of its first +/// evaluation; an edge past the panel reads the first interval and the first +/// pair, whose finite coefficients its zero amplitude then replaces. +template +__device__ __forceinline__ void panel_radial( + const BlockArguments& block, + const PanelEdges& edges, + float* operand, + float (&slope)[RadialPanel::Items]) { + using R = RadialPanel; + constexpr int Channels = L::Channels; + const Arguments& args = block.edges; + constexpr int Batch = R::Items < kAmplitudeBatch ? R::Items : kAmplitudeBatch; + static_assert(R::Items % Batch == 0, "the batches cover the items of a lane"); + with_mode_rank(args.radial_modes, [&](auto rank) { + constexpr int Modes = decltype(rank)::value; +#pragma unroll + for (int n0 = 0; n0 < R::Items; n0 += Batch) { + TableCoefficients coefficients[Batch]; + float2 film[Batch]; +#pragma unroll + for (int b = 0; b < Batch; ++b) { + const RadialItem item = R::item(n0 + b); + const TableRow row = + table_row(args.table, {edges.interval[item.edge], 0.0f, false}, + args.table_width); + coefficients[b] = table_coefficients(row, item.channel); + film[b] = __ldg(reinterpret_cast(args.pair_film) + + static_cast(edges.pair[item.edge]) * Channels + + item.channel); + } +#pragma unroll + for (int b = 0; b < Batch; ++b) { + const RadialItem item = R::item(n0 + b); + const int e = item.edge; + const bool active = edges.row[e] >= 0; + const float x = edges.coordinate[e]; + const float envelope = edges.envelope[e]; + const float* mixing = + args.pair_mixing + + (static_cast(edges.pair[e]) * Channels + item.channel) * + Modes; + float value; + if constexpr (L::Reverse) { + const float2 radial = + spline_value_with_derivative(coefficients[b], x, false); + value = fmaf(radial.x, film[b].x, film[b].y); + float derivative = radial.y * film[b].x; + if constexpr (Modes > 0) { + accumulate_modes_with_derivative(mixing, edges.modes[e], + edges.mode_slopes[e], Modes, value, + derivative); + } + if (args.bridged) { + derivative *= edges.seen_slope[e]; + } + slope[n0 + b] = active ? fmaf(edges.envelope_slope[e], value, + envelope * derivative) + : 0.0f; + } else { + value = fmaf(spline_value(coefficients[b], x), film[b].x, film[b].y); + if constexpr (Modes > 0) { + accumulate_modes(mixing, edges.modes[e], Modes, value); + } + } + operand[(L::B::Fields + item.channel) * L::Stride + e] = + active ? value * envelope : 0.0f; + } + } + }); +} + +/// The radial cotangent of every edge of a panel, the sum over its channels of +/// the amplitude cotangent times the radial derivative of the amplitude, into +/// ``total`` (Edges). The amplitude cotangents are in the channel rows of the +/// operand and the derivatives in the items of the lanes (panel_radial). The +/// eight channels of an octet are summed by a butterfly over the lanes of the +/// octet into ``partial`` (Octets, Edges), and the octets in ascending order; +/// a barrier precedes the use of ``total``. +template +__device__ __forceinline__ void radial_cotangent( + const float* operand, + const float (&slope)[RadialPanel::Items], + float* partial, + float* total) { + using R = RadialPanel; +#pragma unroll + for (int n = 0; n < R::Items; ++n) { + const RadialItem item = R::item(n); + float value = + operand[(L::B::Fields + item.channel) * L::Stride + item.edge] * + slope[n]; + value += __shfl_xor_sync(0xffffffffu, value, 1); + value += __shfl_xor_sync(0xffffffffu, value, 2); + value += __shfl_xor_sync(0xffffffffu, value, 4); + if (threadIdx.x % 8 == 0) { + partial[(item.channel / 8) * L::Edges + item.edge] = value; + } + } + __syncthreads(); + for (int e = threadIdx.x; e < L::Edges; e += kBlockThreads) { + float value = 0.0f; +#pragma unroll + for (int octet = 0; octet < R::Octets; ++octet) { + value += partial[octet * L::Edges + e]; + } + total[e] = value; + } +} + +/// The values of the tile of a lane in the channel rows of the operand. +template +__device__ __forceinline__ void load_tile(const float* operand, + int e0, + int c0, + float (&values)[L::TE][L::TC]) { +#pragma unroll + for (int i = 0; i < L::TE; ++i) { +#pragma unroll + for (int j = 0; j < L::TC; ++j) { + values[i][j] = operand[(L::B::Fields + c0 + j) * L::Stride + e0 + i]; + } + } +} + +/// The source terms that a product of the tile of a lane adds to its +/// accumulators: the ``TC`` source features from ``offset`` of the source of +/// every edge of the tile, zero past the panel. A product requests them ahead +/// of its contraction and adds them after it, so that the contraction does not +/// wait for them. +template +__device__ __forceinline__ void load_source_terms( + const BlockArguments& block, + const PanelEdges& edges, + int offset, + int e0, + int c0, + float (&terms)[L::TE][L::TC]) { + using B = typename L::B; +#pragma unroll + for (int i = 0; i < L::TE; ++i) { + const long source = edges.source[e0 + i]; + if (source >= 0) { + load_floats_cached( + block.sources + source * B::SourceWidth + offset + c0, terms[i]); + } else { +#pragma unroll + for (int j = 0; j < L::TC; ++j) { + terms[i][j] = 0.0f; + } + } + } +} + +/// The amplitudes of the tile of a lane from the channel rows of the operand, +/// where panel_radial left them, replaced there by their saturation. The +/// transport weight of every edge, a sum over its channels, is summed over +/// the channel tiles of the warp into the partial sum of its channel group, +/// ``(ChannelGroups, Heads, Edges)``, which close_channel_groups completes. +template +__device__ __forceinline__ void panel_amplitudes(const float* record, + int e0, + int c0, + float (&phi)[L::TE][L::TC], + float* operand, + const PanelTile& tile, + float* tau_partial) { + using B = typename L::B; + const float knee = __ldg(record + 3); + load_tile(operand, e0, c0, phi); +#pragma unroll + for (int i = 0; i < L::TE; ++i) { + float tau[B::Heads] = {}; +#pragma unroll + for (int j = 0; j < L::TC; ++j) { + const int c = c0 + j; + const float saturated = soft_saturate(phi[i][j], knee); + operand[(B::Fields + c) * L::Stride + e0 + i] = saturated; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + tau[h] = + fmaf(saturated, __ldg(record + B::EdgeTransport + c * B::Heads + h), + tau[h]); + } + } +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + const float total = tile_sum(tau[h]); + if (tile.leader) { + tau_partial[(tile.group * B::Heads + h) * L::Edges + e0 + i] = total; + } + } + } +} + +/// Stage both edge maps of a block record in shared memory: [W_F; W_phi] and +/// [G; W_O], each (Operand, Channels) and contiguous in the record. +template +__device__ __forceinline__ void stage_edge_maps(const float* record, + float* hidden, + float* logit) { + constexpr int Floats = B::Operand * B::P::C0; + for (int index = threadIdx.x * 4; index < Floats; + index += kBlockThreads * 4) { + *reinterpret_cast(hidden + index) = + __ldg(reinterpret_cast(record + B::EdgeField + index)); + *reinterpret_cast(logit + index) = + __ldg(reinterpret_cast(record + B::EdgeGain + index)); + } +} + +/// Shared memory of the forward scan: the per-edge state, the operand, the +/// partial transport weights of the channel groups and the row sums, then +/// both edge maps when ``Resident`` and the stage of the streamed weights +/// otherwise. +template +constexpr size_t block_forward_shared_bytes() { + using B = typename L::B; + return panel_operand_offset() + + sizeof(float) * + (B::Operand * L::Stride + L::ChannelGroups * B::Heads * L::Edges + + kBlockRows * (B::GeometricWidth + B::TransportWidth) + + (Resident ? 2 * B::Operand * L::Channels + : weight_stage_floats())); +} + +/// The edge scan of a further block over a block of destination rows: the +/// moments of the first block corrected by the edges inside the cutoff of the +/// block, the transported keys, and their denominators, in the state layout +/// of the first block. Its products read the edge maps from shared memory when +/// ``Resident`` and stream them otherwise, in the same order. +template +__global__ __launch_bounds__( + kBlockThreads, + BlockPanel:: + MinBlocks) void block_forward_kernel(BlockArguments block) { + using P = Profile; + using L = PanelLayout; + using B = typename L::B; + using R = RadialPanel; + constexpr int TE = L::TE; + constexpr int TC = L::TC; + constexpr int Stride = L::Stride; + // Row sums: the corrections of the geometric moments, the softmax + // denominators, then the transported keys. + constexpr int Sums = B::GeometricWidth + B::TransportWidth; + constexpr int DenominatorSum = B::GeometricWidth; + constexpr int TransportSum = B::GeometricWidth + B::Heads; + const Arguments& args = block.edges; + const float* record = block.record; + const float logit_cap = __ldg(record + 4); + const float null_floor = __ldg(record + 5); + const PanelTile tile = panel_tile(); + const int c0 = tile.c0; + const int e0 = tile.e0; + __shared__ ScanRows scan; + const int block_rows = device_block_rows(block); + const int rows = scan_row_count(block, block_rows); + if (rows == 0) { + return; + } + locate_scan_rows(block, block_rows, rows, scan); + + extern __shared__ __align__(16) float block_shared[]; + auto& edges = *reinterpret_cast*>(block_shared); + float* operand = block_shared + panel_operand_offset() / sizeof(float); + float* tau_partial = operand + B::Operand * Stride; + auto* sums = reinterpret_cast( + tau_partial + L::ChannelGroups * B::Heads * L::Edges); + const float* hidden_map = record + B::EdgeField; + const float* logit_map = record + B::EdgeGain; + float* const weights = reinterpret_cast(sums) + kBlockRows * Sums; + if constexpr (Resident) { + stage_edge_maps(record, weights, weights + B::Operand * Channels); + hidden_map = weights; + logit_map = weights + B::Operand * Channels; + } + for (int index = threadIdx.x; index < kBlockRows * Sums; + index += kBlockThreads) { + sums[index / Sums][index % Sums] = 0.0f; + } + __syncthreads(); + const long edge_end = scan.edges(); + prefetch_block_bonds(args, scan); + + for (long panel = 0; panel < edge_end; panel += L::Edges) { + __syncthreads(); + load_panel_edges(block, scan, panel, edges, nullptr, operand, + edges.keys[0]); + __syncthreads(); + float no_slope[R::Items]; + panel_radial(block, edges, operand, no_slope); + __syncthreads(); + float phi[TE][TC]; + panel_amplitudes(record, e0, c0, phi, operand, tile, tau_partial); + __syncthreads(); + close_channel_groups(tau_partial, edges.tau[0], B::Heads); + + // === Hidden layer: [F, sat(phi)] [W_F; W_phi] + h_j === + float terms[TE][TC]; + load_source_terms(block, edges, B::SourceHidden, e0, c0, terms); + float acc[TE][TC] = {}; + panel_product( + operand, hidden_map, weights, e0, c0, acc, panel != 0, logit_map); + __syncthreads(); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + operand[(B::Fields + c0 + j) * Stride + e0 + i] = + block_silu(acc[i][j] + terms[i][j]); + } + } + __syncthreads(); + + // === Logit: [F, silu(hid)] [G; W_O] + s_j === + load_source_terms(block, edges, B::SourceState, e0, c0, terms); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] = 0.0f; + } + } + panel_product() % 2>( + operand, logit_map, weights, e0, c0, acc, true, + panel + L::Edges < edge_end ? hidden_map : nullptr); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] += terms[i][j]; + } + } + __syncthreads(); + + // === Correction amplitudes and softmax masses === +#pragma unroll + for (int i = 0; i < TE; ++i) { + const int e = e0 + i; + const float block_envelope = edges.block_envelope[e]; +#pragma unroll + for (int j = 0; j < TC; ++j) { + const int c = c0 + j; + const float logit = acc[i][j]; + operand[(B::Fields + c) * Stride + e] = + phi[i][j] * block_envelope * tanhf(logit); + if (c < B::Heads) { + const float weight = edges.envelope[e] * block_envelope; + edges.mass[c][e] = + weight * weight * __expf(logit_cap * tanhf(logit / logit_cap)); + } + } + } + __syncthreads(); + + // === Row sums === + add_row_sums( + edges.rows, Sums, + [&](int component) { + if (component < Channels) { + return RowProduct{operand + (B::Fields + component) * Stride, + nullptr, nullptr}; + } + if (component < B::GeometricWidth) { + int degree, harmonic, channel; + decode_angular(component, degree, harmonic, channel); + return RowProduct{edges.envelope, + operand + (B::Fields + channel) * Stride, + edges.basis[degree * degree + harmonic]}; + } + if (component < TransportSum) { + return RowProduct{edges.mass[component - DenominatorSum], nullptr, + nullptr}; + } + const int q = component - TransportSum; + const int head = q % B::Heads; + return RowProduct{edges.mass[head], edges.tau[head], edges.keys[q]}; + }, + &sums[0][0], Sums); + } + __syncthreads(); + + // === Moments of the block in the state layout of the first block === + for (int index = threadIdx.x; index < rows * P::StateWidth; + index += kBlockThreads) { + const int r = index / P::StateWidth; + const int coordinate = index % P::StateWidth; + const long row = scan.row[r]; + const long node = args.node_begin + row; + const float* first = block.first_state + node * P::StateWidth; + float value = first[coordinate]; + if (coordinate < Channels) { + value = fmaf(sums[r][coordinate], first[P::MomentWidth], value); + } else if (coordinate < B::GeometricWidth) { + int degree, component, channel; + decode_angular(coordinate, degree, component, channel); + const float* output = record + B::output_offset(degree); + const int harmonic = B::harmonic_offset(degree) + component; + float transported = 0.0f; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + const float denominator = sums[r][DenominatorSum + h] + + softplus(block.centers[node * B::Heads + h]) + + null_floor; + transported = fmaf( + sums[r][TransportSum + harmonic * B::Heads + h] / denominator, + __ldg(output + h * B::width_of(degree) + channel), transported); + } + value = fmaf(sums[r][coordinate], first[P::MomentWidth + 1], value) + + transported; + } + block.state_out[row * P::StateWidth + coordinate] = value; + } + for (int index = threadIdx.x; index < rows * B::TransportWidth; + index += kBlockThreads) { + const int r = index / B::TransportWidth; + const int q = index % B::TransportWidth; + const long row = scan.row[r]; + const long node = args.node_begin + row; + const int h = q < B::KeyWidth ? q % B::Heads : q - B::KeyWidth; + const float denominator = sums[r][DenominatorSum + h] + + softplus(block.centers[node * B::Heads + h]) + + null_floor; + block.transport[row * B::TransportWidth + q] = + q < B::KeyWidth ? sums[r][TransportSum + q] / denominator : denominator; + } +} + +/// Per-edge arrays of the backward scan after the operand, each value-major: +/// the radial and block-envelope cotangents of the amplitudes, their part +/// that the source gate reads, the field cotangents, the correction +/// amplitudes of the channels of degree one, the destination cotangents of +/// the transport and of the denominators (padded rows), and the +/// transport-weight cotangents, the key products and the weight cotangents of +/// the masses. The partial sums of the channel groups, of the per-head sums +/// and of the octets of the radial cotangents (radial_cotangent), form a +/// section of their own, which a scan that streams its weights keeps in the +/// stage of the weights: they are written and read between the products only. +template +struct BackwardPanel { + using B = typename L::B; + static constexpr int Edges = L::Edges; + static constexpr int Radial = 0; + static constexpr int Envelope = Radial + Edges; + /// Sum over the channels of the amplitude cotangents times the amplitudes, + /// for the source gate of a bridged descriptor. + static constexpr int GateTotal = Envelope + Edges; + static constexpr int FieldGradient = GateTotal + Edges; + static constexpr int DeltaLow = FieldGradient + B::Fields * Edges; + static constexpr int TransportCotangent = DeltaLow + B::P::C1 * Edges; + static constexpr int TransportCotangentWidth = B::KeyWidth + B::Heads; + // The padded rows end on a 16-byte boundary, as every array does. + static constexpr int TauGradient = aligned_floats( + TransportCotangent + TransportCotangentWidth * (Edges + 1)); + static constexpr int Product = TauGradient + B::Heads * Edges; + static constexpr int MassWeight = Product + B::Heads * Edges; + static constexpr int Floats = MassWeight + B::Heads * Edges; + + static constexpr int GroupPartial = 0; + static constexpr int OctetPartial = + GroupPartial + L::ChannelGroups * B::Heads * Edges; + static constexpr int PartialFloats = + OctetPartial + RadialPanel::Octets * Edges; +}; + +/// Shared memory of the backward scan: the per-edge state, the operand, the +/// per-edge arrays of BackwardPanel, the keys of the rows and the row sums, +/// then the partial sums of the channel groups and both edge maps with the +/// transposes of their square parts when ``Resident``, and otherwise the +/// stage of the streamed weights, which holds the partial sums between the +/// products. +template +constexpr size_t block_backward_shared_bytes() { + using B = typename L::B; + using A = BackwardPanel; + constexpr int Channels = L::Channels; + constexpr int Stage = weight_stage_floats(); + return panel_operand_offset() + + sizeof(float) * + (B::Operand * L::Stride + A::Floats + + kBlockRows * (B::KeyWidth + B::SourceWidth + 13) + + (Resident + ? A::PartialFloats + 2 * B::Operand * Channels + + 2 * Channels * Channels + : (Stage > A::PartialFloats ? Stage : A::PartialFloats))); +} + +/// The backward of a further block over a block of source rows: every entry +/// of a row is read as the edge the row emits, the forward of the edge is +/// recomputed from the source features of the row, and its cotangents follow +/// from the destination cotangents of the entry's node. The row accumulates +/// the cotangent of its source features and its share of the force and the +/// virial; the destination share of the force lands in fixed point. Its +/// products read the edge maps and their transposes from shared memory when +/// ``Resident`` and stream them otherwise, in the same order. +template +__global__ __launch_bounds__( + kBlockThreads, + BlockPanel:: + MinBlocks) void block_backward_kernel(BlockArguments block) { + using P = Profile; + using L = PanelLayout; + using B = typename L::B; + using A = BackwardPanel; + using R = RadialPanel; + constexpr int TE = L::TE; + constexpr int TC = L::TC; + constexpr int Stride = L::Stride; + constexpr int Edges = L::Edges; + // Row sums: the cotangent of the source features, then the force and the + // virial of the edges the row emits, and the gate total of the row under a + // source gate. + constexpr int Sums = B::SourceWidth + 13; + constexpr int ForceSum = B::SourceWidth; + constexpr int VirialSum = B::SourceWidth + 3; + constexpr int GateSum = B::SourceWidth + 12; + const Arguments& args = block.edges; + const float* record = block.record; + const float amplitude_knee = __ldg(record + 3); + const float logit_cap = __ldg(record + 4); + const PanelTile tile = panel_tile(); + const int c0 = tile.c0; + const int e0 = tile.e0; + __shared__ ScanRows scan; + const int block_rows = device_block_rows(block); + const int rows = scan_row_count(block, block_rows); + if (rows == 0) { + return; + } + locate_scan_rows(block, block_rows, rows, scan); + + extern __shared__ __align__(16) float block_shared[]; + auto& edges = *reinterpret_cast*>(block_shared); + float* operand = block_shared + panel_operand_offset() / sizeof(float); + float* panel = operand + B::Operand * Stride; + float* radial_total = panel + A::Radial; + float* envelope_total = panel + A::Envelope; + float* gate_total = panel + A::GateTotal; + const bool gated = args.source_gate != nullptr; + auto* field_gradient = + reinterpret_cast(panel + A::FieldGradient); + auto* delta_low = reinterpret_cast(panel + A::DeltaLow); + auto* transport_cotangent = + reinterpret_cast(panel + A::TransportCotangent); + auto* tau_gradient = + reinterpret_cast(panel + A::TauGradient); + // P_i . K_j, the destination cotangent of the transport against the keys. + auto* product = reinterpret_cast(panel + A::Product); + auto* mass_weight = reinterpret_cast(panel + A::MassWeight); + // The keys of the rows, the sources of every edge of the backward. + auto* row_keys = reinterpret_cast(panel + A::Floats); + auto* sums = reinterpret_cast(row_keys + kBlockRows); + const float* hidden_map = record + B::EdgeField; + const float* logit_map = record + B::EdgeGain; + const float* hidden_map_t = record + B::EdgeAmplitudeT; + const float* logit_map_t = record + B::EdgeOutputT; + // The partial sums of the channel groups, reused for every per-head sum + // over channels, and those of the octets of the radial cotangents: before + // the edge maps when they are resident, and in the stage of the streamed + // weights otherwise, whose products a barrier separates from their use. + float* const partials = reinterpret_cast(sums + kBlockRows); + float* const weights = Resident ? partials + A::PartialFloats : partials; + float* group_partial = partials + A::GroupPartial; + float* octet_partial = partials + A::OctetPartial; + // A barrier between a product and a use of the partial sums when they share + // the stage of its weights. + const auto release_stage = [] { + if constexpr (!Resident) { + __syncthreads(); + } + }; + if constexpr (Resident) { + float* staged = weights; + float* staged_t = staged + 2 * B::Operand * Channels; + stage_edge_maps(record, staged, staged + B::Operand * Channels); + for (int index = threadIdx.x * 4; index < Channels * Channels; + index += kBlockThreads * 4) { + *reinterpret_cast(staged_t + index) = __ldg( + reinterpret_cast(record + B::EdgeAmplitudeT + index)); + *reinterpret_cast(staged_t + Channels * Channels + index) = + __ldg( + reinterpret_cast(record + B::EdgeOutputT + index)); + } + hidden_map = staged; + logit_map = staged + B::Operand * Channels; + hidden_map_t = staged_t; + logit_map_t = staged_t + Channels * Channels; + } + for (int index = threadIdx.x; index < kBlockRows * Sums; + index += kBlockThreads) { + sums[index / Sums][index % Sums] = 0.0f; + } + __syncthreads(); + const long edge_end = scan.edges(); + prefetch_block_bonds(args, scan); + for (int index = threadIdx.x; index < rows * B::KeyWidth; + index += kBlockThreads) { + const int r = index / B::KeyWidth; + const int q = index % B::KeyWidth; + row_keys[r][q] = + block.sources[(args.node_begin + scan.row[r]) * B::SourceWidth + q]; + } + + for (long panel_begin = 0; panel_begin < edge_end; panel_begin += Edges) { + __syncthreads(); + // The destination cotangents of the transport and of the denominators of + // every edge arrive with its geometry. + load_panel_edges(block, scan, panel_begin, edges, row_keys, + operand, transport_cotangent[0]); + for (int index = threadIdx.x; index < Edges * B::Heads; + index += kBlockThreads) { + const int e = index % Edges; + const int h = index / Edges; + const float* keys = row_keys[max(edges.row[e], 0)]; + float value = 0.0f; + for (int harmonic = 0; harmonic < B::Harmonics; ++harmonic) { + const int q = harmonic * B::Heads + h; + value = fmaf(transport_cotangent[q][e], keys[q], value); + } + product[h][e] = value; + } + float slope[R::Items]; + panel_radial(block, edges, operand, slope); + __syncthreads(); + float phi[TE][TC]; + panel_amplitudes(record, e0, c0, phi, operand, tile, group_partial); + __syncthreads(); + close_channel_groups(group_partial, edges.tau[0], B::Heads); + release_stage(); + + // === Recompute the hidden layer and the logit === + // The source of every entry is the row, as in the forward of its edge. + float terms[TE][TC]; + load_source_terms(block, edges, B::SourceHidden, e0, c0, terms); + float acc[TE][TC] = {}; + float activation_slope[TE][TC]; + panel_product( + operand, hidden_map, weights, e0, c0, acc, false, logit_map); + __syncthreads(); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + const float hidden = acc[i][j] + terms[i][j]; + activation_slope[i][j] = block_silu_slope(hidden); + operand[(B::Fields + c0 + j) * Stride + e0 + i] = block_silu(hidden); + } + } + __syncthreads(); + load_source_terms(block, edges, B::SourceState, e0, c0, terms); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] = 0.0f; + } + } + panel_product() % 2>( + operand, logit_map, weights, e0, c0, acc, true); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] += terms[i][j]; + } + } + + // === Cotangent of the logit === + float amplitude_gradient[TE][TC]; + float block_part[TE] = {}; +#pragma unroll + for (int i = 0; i < TE; ++i) { + const int e = e0 + i; + const bool active = edges.row[e] >= 0; + const float* cotangent = + block.cotangents + (active ? edges.node[e] : 0) * B::CotangentWidth; + const float envelope = edges.envelope[e]; + const float block_envelope = edges.block_envelope[e]; + // dE/d(delta_c) of the channels of the tile: the scalar moment and + // every angular moment that carries the channel, each with its harmonic + // and second envelope. The channels of a component are contiguous and a + // tile lies inside or outside a degree of two or more channels, so the + // tile loads as one vector per component. + float d_delta[TC] = {}; + if (active) { + load_floats_cached(cotangent + c0, d_delta); +#pragma unroll + for (int degree = 1; degree <= Lmax; ++degree) { + const int width = B::width_of(degree); + if (c0 < width) { + float angular[TC] = {}; + for (int m = 0; m < 2 * degree + 1; ++m) { + const float* moment = + cotangent + moment_coordinate(degree, m, c0); + float values[TC] = {}; + if (width == 1) { + values[0] = __ldg(moment); + } else { + load_floats_cached(moment, values); + } + const float harmonic = edges.basis[degree * degree + m][e]; +#pragma unroll + for (int j = 0; j < TC; ++j) { + angular[j] = fmaf(values[j], harmonic, angular[j]); + } + } +#pragma unroll + for (int j = 0; j < TC; ++j) { + if (c0 + j < width) { + d_delta[j] = fmaf(envelope, angular[j], d_delta[j]); + } + } + } + } + } +#pragma unroll + for (int j = 0; j < TC; ++j) { + const int c = c0 + j; + const float logit = acc[i][j]; + const float slope_tanh = tanhf(logit); + const float t = block_envelope * slope_tanh; + const float d_t = d_delta[j] * phi[i][j]; + block_part[i] = fmaf(d_t, slope_tanh, block_part[i]); + float d_logit = d_t * block_envelope * (1.0f - slope_tanh * slope_tanh); + if (c < B::Heads) { + const float capped = tanhf(logit / logit_cap); + const float weight = envelope * block_envelope; + const float exponential = __expf(logit_cap * capped); + const float mass = active ? weight * weight * exponential : 0.0f; + const float d_mass = transport_cotangent[B::KeyWidth + c][e] + + edges.tau[c][e] * product[c][e]; + d_logit = fmaf(d_mass * mass, 1.0f - capped * capped, d_logit); + tau_gradient[c][e] = mass * product[c][e]; + edges.mass[c][e] = mass; + // dE/dw for the weight w = chi chi_k of the mass. + mass_weight[c][e] = + active ? d_mass * 2.0f * weight * exponential : 0.0f; + } + amplitude_gradient[i][j] = d_delta[j] * t; + acc[i][j] = active ? d_logit : 0.0f; + if (c < P::C1) { + delta_low[c][e] = phi[i][j] * t; + } + } + } + release_stage(); +#pragma unroll + for (int i = 0; i < TE; ++i) { + const float total = tile_sum(block_part[i]); + if (tile.leader) { + group_partial[tile.group * Edges + e0 + i] = total; + } + } + __syncthreads(); + close_channel_groups(group_partial, envelope_total, 1); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + operand[(B::Fields + c0 + j) * Stride + e0 + i] = acc[i][j]; + } + } + __syncthreads(); + + // === State cotangent of the row === + add_row_sums( + edges.rows, Channels, + [&](int c) { + return RowProduct{operand + (B::Fields + c) * Stride, nullptr, + nullptr}; + }, + &sums[0][B::SourceState], Sums); + + // === Field cotangent === + // The fields enter both maps, so their cotangent is the sum of the logit + // and the hidden-layer cotangents through the field rows of [G; W_O] and + // [W_F; W_phi], each formed while the operand holds its cotangent. + field_cotangent(operand, logit_map, field_gradient[0]); + + // === dsilu = dlogit W_O^T, dhid = dsilu silu'(hid) === +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] = 0.0f; + } + } + panel_product( + operand + B::Fields * Stride, logit_map_t, weights, e0, c0, acc, false, + hidden_map_t); + __syncthreads(); + // The hidden-layer cotangent replaces the logit cotangent of the tile of + // the lane in the operand. +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + operand[(B::Fields + c0 + j) * Stride + e0 + i] = + edges.row[e0 + i] >= 0 ? acc[i][j] * activation_slope[i][j] : 0.0f; + } + } + __syncthreads(); + field_cotangent(operand, hidden_map, field_gradient[0]); + + // === Hidden-layer cotangent of the row === + add_row_sums( + edges.rows, Channels, + [&](int c) { + return RowProduct{operand + (B::Fields + c) * Stride, nullptr, + nullptr}; + }, + &sums[0][B::SourceHidden], Sums); + + // === dsat = dhid W_phi^T + dtau W_T^T, then the radial cotangent === +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + acc[i][j] = 0.0f; + } + } + panel_product() % 2>( + operand + B::Fields * Stride, hidden_map_t, weights, e0, c0, acc, true); +#pragma unroll + for (int i = 0; i < TE; ++i) { + const int e = e0 + i; +#pragma unroll + for (int j = 0; j < TC; ++j) { + const int c = c0 + j; + float d_saturated = acc[i][j]; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + d_saturated = fmaf( + tau_gradient[h][e], + __ldg(record + B::EdgeTransport + c * B::Heads + h), d_saturated); + } + acc[i][j] = + fmaf(d_saturated, soft_saturate_slope(phi[i][j], amplitude_knee), + amplitude_gradient[i][j]); + } + } + // The amplitude cotangents replace the hidden-layer cotangents in the + // channel rows of the operand once every lane has read them. + __syncthreads(); +#pragma unroll + for (int i = 0; i < TE; ++i) { +#pragma unroll + for (int j = 0; j < TC; ++j) { + operand[(B::Fields + c0 + j) * Stride + e0 + i] = acc[i][j]; + } + } + if (gated) { + // Under a source gate the envelope of an edge enters the gates of the + // other edges of its source: the cotangent of the envelope times the + // envelope takes the sum over the channels of the amplitude cotangents + // times the amplitudes, which carry the envelope. +#pragma unroll + for (int i = 0; i < TE; ++i) { + float value = 0.0f; +#pragma unroll + for (int j = 0; j < TC; ++j) { + value = fmaf(acc[i][j], phi[i][j], value); + } + const float total = tile_sum(value); + if (tile.leader) { + group_partial[tile.group * Edges + e0 + i] = total; + } + } + } + __syncthreads(); + radial_cotangent(operand, slope, octet_partial, radial_total); + if (gated) { + close_channel_groups(group_partial, gate_total, 1); + } + __syncthreads(); + + // === Per-edge gradient, force and virial === + for (int e = threadIdx.x; e < Edges; e += kBlockThreads) { + const int row = edges.row[e]; + if (row < 0) { + continue; + } + const float* cotangent = + block.cotangents + edges.node[e] * B::CotangentWidth; + const float envelope = edges.envelope[e]; + const float block_envelope = edges.block_envelope[e]; + float block_total = envelope_total[e]; + float weight_total = 0.0f; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + weight_total += mass_weight[h][e]; + } + // The angular moments carry the harmonic and the second envelope of the + // correction amplitude of every low channel. + float d_basis[L::BasisWidth] = {}; + float envelope_part = weight_total * block_envelope; + block_total = fmaf(weight_total, envelope, block_total); +#pragma unroll + for (int degree = 1; degree <= Lmax; ++degree) { + const float reflection = degree % 2 == 0 ? 1.0f : -1.0f; + const int width = B::width_of(degree); + for (int m = 0; m < 2 * degree + 1; ++m) { + const float* moment = cotangent + moment_coordinate(degree, m, 0); + float payload = 0.0f; + if (width == 1) { + payload = __ldg(moment) * delta_low[0][e]; + } else { + for (int c = 0; c < width; c += 4) { + float values[4]; + load_floats_cached<4>(moment + c, values); +#pragma unroll + for (int k = 0; k < 4; ++k) { + payload = fmaf(values[k], delta_low[c + k][e], payload); + } + } + } + const float harmonic = edges.basis[degree * degree + m][e]; + envelope_part = fmaf(payload, harmonic, envelope_part); + float field = 0.0f; +#pragma unroll + for (int h = 0; h < B::Heads; ++h) { + field = fmaf( + row_keys[row][(B::harmonic_offset(degree) + m) * B::Heads + h], + field_gradient[(degree - 1) * B::Heads + h][e], field); + } + d_basis[degree * degree + m] = + fmaf(envelope, payload, reflection * field); + } + } + const float x = edges.vector[0][e]; + const float y = edges.vector[1][e]; + const float z = edges.vector[2][e]; + const EdgeGeometry geometry = block_geometry(x, y, z, args.eps); + const float radial_gradient = radial_total[e] + + envelope_part * edges.envelope_slope[e] + + block_total * edges.block_slope[e]; + if (gated) { + // The cotangent of the envelope times the envelope, which joins the + // gate total of the row, the source of every entry; the radial + // cotangent above was its last reader. + radial_total[e] = fmaf(envelope, envelope_part, gate_total[e]); + } + float low[9]; +#pragma unroll + for (int index = 0; index < 9; ++index) { + low[index] = index < L::BasisWidth ? d_basis[index] : 0.0f; + } + float direction[3] = {0.0f, 0.0f, 0.0f}; + if constexpr (Lmax >= 3) { +#pragma unroll + for (int index = 0; index < (Lmax >= 4 ? 16 : 7); ++index) { + high_basis_gradient(geometry, index, d_basis[9 + index], direction); + } + } + float gradient[3]; + basis_vjp(geometry, low, direction, radial_gradient, gradient); + // The edge emitted by the row points from its destination to the row: + // the destination gains +g and the row -g, and the virial -g (x) v. + unsigned long long* const words = + args.force + edges.node[e] * kForceWords; +#pragma unroll + for (int component = 0; component < 3; ++component) { + check_force_range(gradient[component], words); + atomicAdd(words + component, fixed_point(gradient[component])); + } + // The row share of the edge waits in the leading rows of the operand, + // which the panel no longer reads, for the row sums below. +#pragma unroll + for (int component = 0; component < 3; ++component) { + operand[component * Stride + e] = -gradient[component]; + } +#pragma unroll + for (int component = 0; component < 9; ++component) { + operand[(3 + component) * Stride + e] = + -gradient[component / 3] * edges.vector[component % 3][e]; + } + } + __syncthreads(); + + // === Key cotangent, force and virial of every row === + // The fields read the row's keys along the reversed bond, and the + // transport scales them by the mass, the transport weight and the + // destination cotangent. The force, the virial and the gate total of the + // rows follow on the warps after those of the keys. + constexpr int KeyParts = row_sum_parts(B::KeyWidth + 13); + add_row_sums( + edges.rows, B::KeyWidth, + [&](int component) { + const int harmonic = component / B::Heads; + const int h = component % B::Heads; + const int degree = harmonic_degree(harmonic); + const float reflection = degree % 2 == 0 ? 1.0f : -1.0f; + const float* basis = edges.basis[1 + harmonic]; + const float* field = field_gradient[(degree - 1) * B::Heads + h]; + const float* mass = edges.mass[h]; + const float* tau = edges.tau[h]; + const float* cotangent = transport_cotangent[component]; + return [=](int e) { + return fmaf(reflection * basis[e], field[e], + mass[e] * tau[e] * cotangent[e]); + }; + }, + &sums[0][0], Sums); + add_row_sums( + edges.rows, gated ? 13 : 12, + [&](int component) { + return RowProduct{ + component < 12 ? operand + component * Stride : radial_total, + nullptr, nullptr}; + }, + &sums[0][ForceSum], Sums, row_sum_lanes(B::KeyWidth)); + } + __syncthreads(); + + // === Source cotangents, row force and virial === + for (int index = threadIdx.x; index < rows * B::SourceWidth; + index += kBlockThreads) { + const int r = index / B::SourceWidth; + const int q = index % B::SourceWidth; + block.source_gradient[scan.row[r] * B::SourceWidth + q] = sums[r][q]; + } + for (int index = threadIdx.x; index < rows * 12; index += kBlockThreads) { + const int r = index / 12; + const int q = index % 12; + const long row = scan.row[r]; + if (q < 3) { + const long node = args.node_begin + row; + const float value = sums[r][ForceSum + q]; + check_force_range(value, args.force + node * kForceWords); + atomicAdd(args.force + node * kForceWords + q, fixed_point(value)); + } else { + block.source_virial[row * 9 + q - 3] += sums[r][VirialSum + q - 3]; + } + } + if (gated) { + for (int r = threadIdx.x; r < rows; r += kBlockThreads) { + block.gate_sums[args.node_begin + scan.row[r]] += sums[r][GateSum]; + } + } +} + +// === Launch dispatch === + +inline void check_block_status(cudaError_t status, const char* what) { + if (status != cudaSuccess) { + cudaGetLastError(); + TORCH_CHECK(false, "dpa4c: ", what, + " failed: ", cudaGetErrorString(status)); + } +} + +/// The blocks of an edge scan that the device keeps resident at once: those +/// of one multiprocessor, and the multiprocessors. +struct ScanResidency { + int per_multiprocessor = 0; + int multiprocessors = 0; +}; + +/// Raise the dynamic shared memory of ``kernel`` to ``bytes`` once per kernel +/// and device, and return the residency of its blocks on the device, none +/// where a block of the kernel cannot hold that much shared memory. +inline ScanResidency scan_residency(void (*kernel)(BlockArguments), + size_t bytes) { + static std::mutex mutex; + // Keyed by the address of the kernel as an integer, which orders totally. + static std::map, ScanResidency> residencies; + int device = 0; + check_block_status(cudaGetDevice(&device), "the device query"); + const std::pair key{ + reinterpret_cast(kernel), device}; + const std::lock_guard lock(mutex); + const auto known = residencies.find(key); + if (known != residencies.end()) { + return known->second; + } + ScanResidency residency; + check_block_status( + cudaDeviceGetAttribute(&residency.multiprocessors, + cudaDevAttrMultiProcessorCount, device), + "the multiprocessor count"); + int limit = 0; + check_block_status( + cudaDeviceGetAttribute(&limit, cudaDevAttrMaxSharedMemoryPerBlockOptin, + device), + "the shared memory limit of a block"); + cudaFuncAttributes attributes; + check_block_status(cudaFuncGetAttributes(&attributes, kernel), + "the attribute query of a further-block scan"); + // The static and the dynamic shared memory of a block share its limit. + if (attributes.sharedSizeBytes + bytes <= static_cast(limit)) { + check_block_status(cudaFuncSetAttribute( + kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + static_cast(bytes)), + "the shared memory of a further-block scan"); + check_block_status( + cudaOccupancyMaxActiveBlocksPerMultiprocessor( + &residency.per_multiprocessor, kernel, kBlockThreads, bytes), + "the occupancy query of a further-block scan"); + } + residencies.emplace(key, residency); + return residency; +} + +/// Tenths of the time of a full wave of an edge scan that a last wave of one +/// block per multiprocessor takes. Fitted to the LAMMPS steps of the duo +/// grades at 512 to 20,000 atoms with one, two and four rows per block on an +/// RTX PRO 6000 (sm_120), against whose fastest counts the choice of +/// scan_block_rows then loses 0.3% to 0.5% on average and 2.3% at most. +constexpr long kLoneBlockTenths = 7; +static_assert(kLoneBlockTenths >= 0 && kLoneBlockTenths <= 10, + "a last wave takes between nothing and a full wave, which keeps " + "the time of the waves monotone in the blocks"); + +/// The time of the waves of an edge scan over ``nodes`` rows for one, two, +/// ..., kBlockRows rows per block, for blocks of the residency ``residency`` +/// of ``k`` blocks per multiprocessor, in units of ``1 / (10 (k - 1))`` of a +/// full wave, or of a tenth of a full wave for ``k = 1``. The blocks run in +/// waves of the resident blocks of the device; the last wave spreads the +/// remaining blocks over the multiprocessors and takes kLoneBlockTenths tenths +/// of a full wave for one block per multiprocessor, linearly more for more, +/// and the whole wave for ``k``. +inline ScanWaves scan_waves(long nodes, const ScanResidency& residency) { + const long per_multiprocessor = residency.per_multiprocessor; + const long multiprocessors = residency.multiprocessors; + const long resident = per_multiprocessor * multiprocessors; + const long steps = per_multiprocessor > 1 ? per_multiprocessor - 1 : 1; + ScanWaves waves; + for (int choice = 0, rows = 1; choice < kBlockRowCounts; + ++choice, rows *= 2) { + const long blocks = (nodes + rows - 1) / rows; + const long rest = blocks % resident; + long time = 10 * steps * (blocks / resident); + if (rest > 0) { + const long last = (rest + multiprocessors - 1) / multiprocessors; + time += per_multiprocessor > 1 ? kLoneBlockTenths * steps + + (10 - kLoneBlockTenths) * (last - 1) + : 10; + } + waves.time[choice] = time; + } + return waves; +} + +/// Dynamic shared memory up to which an edge scan is compiled with its edge +/// maps resident: two blocks of that size, each with the row state of the +/// scan (ScanRows) and the 1 KB that the device reserves for a block, fill the +/// 228 KB of a multiprocessor of compute capability 9.0 or 10.0, the most of +/// the supported devices. A block of resident maps beyond it keeps a +/// multiprocessor to itself wherever it fits, where the streamed maps keep two +/// blocks or more, so such a scan is compiled with its streamed maps alone. +constexpr size_t kResidentSharedLimit = + 228 * 1024 / 2 - 1024 - sizeof(ScanRows); + +/// A compiled layout of the edge maps of an edge scan: its kernel and the +/// dynamic shared memory of a block. +struct ScanLayout { + void (*kernel)(BlockArguments) = nullptr; + size_t bytes = 0; +}; + +/// Launch an edge scan of panels of ``Edges`` entries over the run of +/// ``arguments``, whose blocks hold ``ResidentBytes`` of shared memory with +/// resident edge maps and ``StreamedBytes`` with streamed ones, with the kernel +/// that ``kernel`` returns for each (std::true_type for the resident maps). The +/// scan is compiled with its resident maps up to kResidentSharedLimit and with +/// its streamed maps where these hold less shared memory; the smaller layout +/// fits a block of every supported device. Where both are compiled, the scan +/// runs with the resident maps if the occupancy of the device keeps at least as +/// many of their blocks on a multiprocessor as of the streamed ones, since the +/// staged maps spare every panel the loads of the streamed weights. Both +/// layouts sum in one order, so the layout changes a result only through the +/// rows of a block, which follow from the residency. +/// +/// The blocks choose their rows from the entries of the graph of the scan over +/// the rows of the whole system, which the device alone holds +/// (device_block_rows); the grid provides for the rows that the edge storage +/// chooses, which holds at least as many entries, so that the blocks take as +/// many rows or more and those past the rows of the run retire. The choice +/// follows from the system and the device alone, so every run of a tiled +/// system takes the same count, and runs of a multiple of kBlockRows rows group +/// the rows as the whole system does. +template +void launch_panel_scan(Kernel kernel, + const BlockArguments& arguments, + cudaStream_t stream) { + constexpr bool HasResident = ResidentBytes <= kResidentSharedLimit; + constexpr bool HasStreamed = ResidentBytes > StreamedBytes; + static_assert(HasResident || HasStreamed, + "every scan is compiled with one layout of its edge maps"); + static_assert( + (HasStreamed ? StreamedBytes : ResidentBytes) <= kPanelSharedLimit, + "the smaller layout of a scan fits every supported device"); + ScanLayout layout; + ScanResidency residency; + if constexpr (HasResident) { + layout = {kernel(std::true_type{}), ResidentBytes}; + residency = scan_residency(layout.kernel, layout.bytes); + } + if constexpr (HasStreamed) { + const ScanLayout streamed{kernel(std::false_type{}), StreamedBytes}; + const ScanResidency other = scan_residency(streamed.kernel, streamed.bytes); + if (!HasResident || + other.per_multiprocessor > residency.per_multiprocessor) { + layout = streamed; + residency = other; + } + } + TORCH_CHECK(residency.per_multiprocessor > 0, + "dpa4c: the device keeps no block of a further-block scan of ", + layout.bytes, " bytes of shared memory resident"); + const long nodes = arguments.edges.system_node_count; + BlockArguments launched = arguments; + launched.waves = scan_waves(nodes, residency); + const int rows = scan_block_rows(launched.waves, nodes, + arguments.edges.edge_count, 1); + launched.grid_rows = rows; + const int blocks = + static_cast((arguments.edges.node_count + rows - 1) / rows); + if (blocks > 0) { + layout.kernel<<>>(launched); + } +} + +template +void launch_block_scan(BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream) { + if (stage == BlockStage::Forward) { + using L = PanelLayout; + launch_panel_scan(), + block_forward_shared_bytes()>( + [](auto resident) { + return block_forward_kernel; + }, + arguments, stream); + } else { + using L = PanelLayout; + launch_panel_scan(), + block_backward_shared_bytes()>( + [](auto resident) { + return block_backward_kernel; + }, + arguments, stream); + } +} + +template +void launch_block_nodes(BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream) { + using P = Profile; + using B = BlockProfile; + const long count = arguments.edges.node_count; + if (count == 0) { + return; + } + // The GEMM tiles of the node maps: tile_index walks the column tiles of + // every row tile of the run. + const auto tiles = [&](int width) { + return static_cast((count + NodeTile::rows - 1) / NodeTile::rows * + ((width + NodeTile::cols - 1) / NodeTile::cols)); + }; + switch (stage) { + case BlockStage::Maps: + block_maps_kernel + <<>>(arguments); + return; + case BlockStage::MapBackward: + block_map_cotangent_kernel + <<>>(arguments); + block_map_input_kernel + <<>>(arguments); + return; + case BlockStage::Cotangents: { + constexpr int Warps = kBlockThreads / kWarpSize; + block_cotangent_kernel + <<((count + Warps - 1) / Warps), kBlockThreads, 0, + stream>>>(arguments); + return; + } + default: + return; + } +} + +template +void launch_block(BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream) { + const Arguments& args = arguments.edges; + const bool scan = + stage == BlockStage::Forward || stage == BlockStage::Backward; + const bool wide = args.index_kind == IndexKind::Bits64; + const auto dispatch = [&](auto modes, auto spin) { + constexpr bool HasModes = decltype(modes)::value; + constexpr bool HasSpin = decltype(spin)::value; + if (!scan) { + launch_block_nodes(stage, arguments, stream); + } else if (wide) { + launch_block_scan( + stage, arguments, stream); + } else { + launch_block_scan( + stage, arguments, stream); + } + }; + const bool modes = args.radial_modes > 0; + if (args.has_spin) { + modes ? dispatch(std::true_type{}, std::true_type{}) + : dispatch(std::false_type{}, std::true_type{}); + } else { + modes ? dispatch(std::true_type{}, std::false_type{}) + : dispatch(std::false_type{}, std::false_type{}); + } +} + +} // namespace deepmd_dpa4c diff --git a/source/op/pt/dpa4c/block_launch.h b/source/op/pt/dpa4c/block_launch.h new file mode 100644 index 0000000000..b7495135c5 --- /dev/null +++ b/source/op/pt/dpa4c/block_launch.h @@ -0,0 +1,266 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// Host-side launch interface of the further message-passing blocks of the +// compressed DPA4C descriptor. +// +// Block k reads per-node features of the edge sources -- keys, an encoded +// state and the neighbor term of an edge hidden layer -- that the node maps +// form from the moments and the invariants of block k - 1, and corrects the +// moments of the first block over the edges inside its own cutoff (see +// deepmd/pt_expt/kernels/dpa4c/attention.py for the equations and the layout +// of the record of a block). Its stages are: +// +// maps node maps of block k from block k - 1: the source features, +// the null-mass logits of every centre and the divisor columns +// of the descriptor; +// forward the edge scan of block k over destination rows, which writes +// the moments of block k in the state layout of the first +// block together with the transport of every row, from which +// the readout of the first block forms the invariants of +// block k; +// cotangents the node part of the backward of block k: from the moment +// gradient of block k, the cotangents of every destination +// that its edges read and the moment gradient carried back to +// the first block; +// backward the edge scan of the backward over source rows: a canonical +// graph holds both directions of every bond, so the entries of +// the row of a source are the edges it emits, and the scan +// accumulates the cotangent of the source features in +// registers instead of scattering it; +// map_backward the backward of the node maps, into the descriptor +// cotangent of block k - 1 and the moment gradient of its keys. +// +// The node set may hold halo rows, which carry no edges; the caller refreshes +// the source features and the destination cotangents of every halo row from +// its owner between the stages (border_exchange.h). + +#pragma once + +#include + +#include "graph_compress_launch.h" + +namespace deepmd_dpa4c { + +/// Attention heads and hidden width of the state encoder of a further block, +/// widths the compiled operator specializes on. +constexpr int kBlockHeads = 2; +constexpr int kBlockStateHidden = 16; +/// Floats of the header of a block record: the cutoff of the block, the knees +/// of the invariant, key and amplitude saturations, the logit cap and the null +/// floor of the softmax, and two padding words. +constexpr int kBlockHeader = 8; + +constexpr int aligned_floats(int count) { return (count + 3) / 4 * 4; } + +/// Widths of a further block and the offsets of the sections of its record, +/// mirroring ``block_layout`` of deepmd/pt_expt/kernels/dpa4c/attention.py. +template +struct BlockProfile { + using P = Profile; + static constexpr int Heads = kBlockHeads; + static constexpr int StateHidden = kBlockStateHidden; + /// Non-scalar harmonic components, those of the keys of a node. + static constexpr int Harmonics = (Lmax + 1) * (Lmax + 1) - 1; + static constexpr int KeyWidth = Harmonics * Heads; + /// Fields of an edge, one per non-scalar degree and head. + static constexpr int Fields = Lmax * Heads; + /// Contraction depth of both edge maps: the fields, then a channel vector. + static constexpr int Operand = Fields + Channels; + + /// Source features of a node: the keys, harmonic-major with the heads + /// innermost, the encoded state and the neighbor term of the hidden layer. + /// The keys are padded to a 16-byte multiple, so that the channels of the + /// state and of the hidden term start on 16-byte boundaries and load as + /// vectors. + static constexpr int SourceState = aligned_floats(KeyWidth); + static constexpr int SourceHidden = SourceState + Channels; + static constexpr int SourceWidth = SourceHidden + Channels; + /// Moments of degrees zero through Lmax, which a further block corrects. + static constexpr int GeometricWidth = P::SpinOffset; + /// Cotangents of a destination that its edges read: the moment gradient of + /// the geometric degrees, then that of the transported keys and of the + /// softmax denominators. A row is padded to a 16-byte multiple, so that the + /// channels of every component of degrees zero through two, which start on + /// 16-byte boundaries, load as vectors. + static constexpr int CotangentTransport = GeometricWidth; + static constexpr int CotangentMass = GeometricWidth + KeyWidth; + static constexpr int CotangentWidth = + aligned_floats(GeometricWidth + KeyWidth + Heads); + /// Transport of a row: the transported keys over their denominators, then + /// the denominators. + static constexpr int TransportWidth = KeyWidth + Heads; + /// Columns of the input layer of the node maps. + static constexpr int NodeHidden = 2 * StateHidden; + static constexpr int NodeNull = NodeHidden + Channels; + static constexpr int NodeWidth = aligned_floats(NodeNull + Heads); + + static constexpr int width_of(int degree) { + return degree == 0 ? P::C0 : degree == 1 ? P::C1 : degree == 2 ? P::C2 : 1; + } + static constexpr int moment_offset(int degree) { + return degree == 0 ? P::ScalarOffset + : degree == 1 ? P::VectorOffset + : degree == 2 ? P::TensorOffset + : degree == 3 ? P::HighOffset + : P::HighOffset + 7; + } + /// First harmonic of a degree from one in the key layout. + static constexpr int harmonic_offset(int degree) { + return degree * degree - 1; + } + + static constexpr int key_offset(int degree) { + int offset = kBlockHeader; + for (int l = 1; l < degree; ++l) { + offset += aligned_floats(width_of(l) * Heads); + } + return offset; + } + static constexpr int NodeWeight = key_offset(Lmax + 1); + static constexpr int NodeBias = NodeWeight + P::OutputWidth * NodeWidth; + static constexpr int StateOutput = NodeBias + NodeWidth; + static constexpr int EdgeField = StateOutput + StateHidden * Channels; + static constexpr int EdgeAmplitude = EdgeField + Fields * Channels; + static constexpr int EdgeGain = EdgeAmplitude + Channels * Channels; + static constexpr int EdgeOutput = EdgeGain + Fields * Channels; + static constexpr int EdgeAmplitudeT = EdgeOutput + Channels * Channels; + static constexpr int EdgeOutputT = EdgeAmplitudeT + Channels * Channels; + static constexpr int EdgeTransport = EdgeOutputT + Channels * Channels; + static constexpr int output_offset(int degree) { + int offset = EdgeTransport + Channels * Heads; + for (int l = 1; l < degree; ++l) { + offset += aligned_floats(Heads * width_of(l)); + } + return offset; + } + static constexpr int Width = output_offset(Lmax + 1); +}; + +/// Destination rows of a block of the edge scans at most, and the numbers of +/// rows that a block may take, the powers of two up to it (scan_block_rows in +/// block_kernel.cuh). +constexpr int kBlockRows = 4; +constexpr int kBlockRowCounts = 3; +static_assert(kBlockRows == 1 << (kBlockRowCounts - 1), + "a block takes the powers of two up to kBlockRows rows"); + +/// The time of the waves of the blocks of an edge scan over the rows of the +/// whole system for one, two, ..., kBlockRows rows per block, in a unit of +/// the scan (scan_waves in block_kernel.cuh). +struct ScanWaves { + long time[kBlockRowCounts] = {}; +}; + +/// Arguments of one stage of a further block over one run of nodes. +/// +/// ``edges`` carries the graph and the radial representation of the first +/// block exactly as the descriptor launches read them, with its node range +/// set to the run. Buffers of the whole node set are indexed by absolute node +/// id, like ``edges.atype``, because the edges of a run read the rows of +/// other runs; buffers of the run are offset by the caller, like +/// ``edges.descriptor``. +struct BlockArguments { + Arguments edges; + /// Record of the block, BlockProfile layout. + const float* record = nullptr; + /// Destination rows per block of the edge scans for which the grid of a + /// launch provides; the blocks take as many or more (scan_block_rows). + int grid_rows = 0; + /// Waves of the blocks of an edge scan, from which they choose their rows. + ScanWaves waves; + /// Rows of the run that the edge scans visit, ascending, and their number, + /// both in device memory; null for every row of the run. The grid of a + /// launch covers every row of the run, and its blocks past the visited rows + /// retire. + const int* scan_rows = nullptr; + const int* scan_row_count = nullptr; + + // === Node set === + /// Moments and norms of the first block, (N, StateWidth). + const float* first_state = nullptr; + /// Moments of block k - 1, (N, StateWidth); the first state for k = 2. + const float* previous_state = nullptr; + /// Source features, (N, SourceWidth). + float* sources = nullptr; + /// Null-mass logits of every centre, (N, Heads). + float* centers = nullptr; + /// Calibrated divisor columns of the descriptor of the first block, which + /// the descriptor of every further block carries, (N, 2). + float* divisors = nullptr; + /// Destination cotangents, (N, CotangentWidth). + float* cotangents = nullptr; + /// Moment gradient of the first block carried back from the further + /// blocks, (N, StateWidth), in the layout of the node backward. + float* carried = nullptr; + /// Whether the cotangent stage adds to ``carried`` rather than writing it. + bool accumulate_carried = false; + + // === Run === + /// Invariants of block k - 1, (run, OutputWidth), read by the node maps. + const float* descriptor = nullptr; + /// Moments and norms of block k, (run, StateWidth). + float* state_out = nullptr; + /// Transport of every row, (run, TransportWidth). + float* transport = nullptr; + /// Node-backward output at the moments of block k, (run, StateWidth). + const float* moment_gradient = nullptr; + /// Cotangent of the null-mass logits, (run, Heads). + float* center_gradient = nullptr; + /// Cotangent of the source features of every row, (run, SourceWidth). + float* source_gradient = nullptr; + /// Virial of the edges every row emits, which the backward adds, (run, 9). + float* source_virial = nullptr; + /// Gate totals of every node of the node set under a source gate + /// (Arguments::source_gate), onto which the backward adds, per row, the sum + /// over the edges the row emits of the envelope cotangent times the + /// envelope; null without a source gate. + float* gate_sums = nullptr; + /// Cotangent of the invariants of block k - 1, (run, OutputWidth); it may + /// take the place of ``descriptor``. + float* descriptor_gradient = nullptr; + /// Moment gradient of the keys of block k, in the node-backward layout of + /// block k - 1, (run, StateWidth). + float* keys_gradient = nullptr; + /// Cotangent of the node input layer of every row, which the backward of the + /// node maps passes between its two kernels, (run, NodeWidth). + float* map_cotangent = nullptr; +}; + +/// Stages of a further block; see the head of this file. +enum class BlockStage : int { + Maps = 0, + Forward = 1, + Cotangents = 2, + Backward = 3, + MapBackward = 4, +}; + +/// Stages of the first block that the composition of several blocks launches +/// one at a time, where a single block launches them together. +enum class FirstStage : int { + /// The invariant readout of ``state_out`` into ``descriptor``. + Readout = 0, + /// The readout VJP of ``descriptor_gradient`` at ``state`` into + /// ``moment_gradient``. + NodeBackward = 1, + /// The edge scans of the backward from ``moment_gradient``. + EdgeBackward = 2, +}; + +/// One stage of a further block for one scalar width and angular degree. Every +/// width of DPA4C_FOR_EACH_CHANNEL and every degree from 2 to 4 is +/// instantiated in a generated block shard (``c_l_block.cu``, +/// configured from dpa4c/shard.cu.in). +template +void launch_block(BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream); + +/// One stage of the first block, instantiated beside launch_forward. +template +void launch_first_stage(FirstStage stage, + const Arguments& arguments, + cudaStream_t stream); + +} // namespace deepmd_dpa4c diff --git a/source/op/pt/dpa4c/graph_compress.cu b/source/op/pt/dpa4c/graph_compress.cu index 48a8aaf062..4db08d7f64 100644 --- a/source/op/pt/dpa4c/graph_compress.cu +++ b/source/op/pt/dpa4c/graph_compress.cu @@ -10,6 +10,8 @@ // and one per width for the others. #include +#include +#include #include #include #include @@ -19,20 +21,33 @@ #include #include #include +#include #include +#include +#include #include #include +#include #include +#include "../border_exchange.h" #include "../canonical_index.h" +#include "../communicator.h" #include "../graph_ops.h" #include "../long_range/charge_sum.h" +#include "../long_range/domain_exchange.h" +#include "block_launch.h" +#include "graph_compress.cuh" #include "graph_compress_launch.h" namespace { using deepmd_dpa4c::Arguments; +using deepmd_dpa4c::BlockArguments; +using deepmd_dpa4c::BlockStage; +using deepmd_dpa4c::FirstStage; using deepmd_dpa4c::IndexKind; +using deepmd_dpa4c::kBlockHeads; using deepmd_dpa4c::kFoldedModes; using deepmd_dpa4c::kForceRangeWord; using deepmd_dpa4c::kForceWords; @@ -144,6 +159,119 @@ void dispatch(int channels, TORCH_CHECK(false, "dpa4c_graph_compress: unsupported channels ", channels); } +template +void dispatch_first_stage_degree(FirstStage stage, + const Arguments& arguments, + cudaStream_t stream) { + switch (arguments.lmax) { + case 2: + deepmd_dpa4c::launch_first_stage(stage, arguments, stream); + return; + case 3: + deepmd_dpa4c::launch_first_stage(stage, arguments, stream); + return; + case 4: + deepmd_dpa4c::launch_first_stage(stage, arguments, stream); + return; + default: + TORCH_CHECK(false, "dpa4c_graph_compress: uncompiled angular degree ", + arguments.lmax); + } +} + +/// One stage of the first block of a descriptor of several blocks. +void dispatch_first_stage(int channels, + FirstStage stage, + const Arguments& arguments, + cudaStream_t stream) { +#define DPA4C_DISPATCH(width) \ + if (channels == width) { \ + dispatch_first_stage_degree(stage, arguments, stream); \ + DPA4C_CHECK_LAUNCH("dpa4c first-block stage"); \ + return; \ + } + DPA4C_FOR_EACH_CHANNEL(DPA4C_DISPATCH) +#undef DPA4C_DISPATCH + TORCH_CHECK(false, "dpa4c_graph_compress: unsupported channels ", channels); +} + +template +void dispatch_block_degree(BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream) { + switch (arguments.edges.lmax) { + case 2: + deepmd_dpa4c::launch_block(stage, arguments, stream); + return; + case 3: + deepmd_dpa4c::launch_block(stage, arguments, stream); + return; + case 4: + deepmd_dpa4c::launch_block(stage, arguments, stream); + return; + default: + TORCH_CHECK(false, "dpa4c_graph_compress: uncompiled angular degree ", + arguments.edges.lmax); + } +} + +/// One stage of a further message-passing block. +void dispatch_block(int channels, + BlockStage stage, + const BlockArguments& arguments, + cudaStream_t stream) { +#define DPA4C_DISPATCH(width) \ + if (channels == width) { \ + dispatch_block_degree(stage, arguments, stream); \ + DPA4C_CHECK_LAUNCH("dpa4c further-block stage"); \ + return; \ + } + DPA4C_FOR_EACH_CHANNEL(DPA4C_DISPATCH) +#undef DPA4C_DISPATCH + TORCH_CHECK(false, "dpa4c_graph_compress: unsupported channels ", channels); +} + +/// Widths of the buffers and of the record of a further block. +struct BlockWidths { + int source; + int cotangent; + int transport; + int node; + int record; +}; + +template +BlockWidths block_widths_of() { + using B = deepmd_dpa4c::BlockProfile; + return {B::SourceWidth, B::CotangentWidth, B::TransportWidth, B::NodeWidth, + B::Width}; +} + +template +BlockWidths block_widths_for(int lmax) { + switch (lmax) { + case 2: + return block_widths_of(); + case 3: + return block_widths_of(); + case 4: + return block_widths_of(); + default: + TORCH_CHECK(false, "dpa4c_graph_compress: unsupported lmax ", lmax); + } +} + +BlockWidths block_widths(int channels, int lmax, bool has_spin) { +#define DPA4C_WIDTHS(width) \ + if (channels == width) { \ + return has_spin ? block_widths_for(lmax) \ + : block_widths_for(lmax); \ + } + DPA4C_FOR_EACH_CHANNEL(DPA4C_WIDTHS) +#undef DPA4C_WIDTHS + TORCH_CHECK(false, "dpa4c_graph_compress: unsupported channels ", channels); +} + /// Immutable tensors and scalars shared by both directions of the operator. struct Payload { torch::Tensor edge_index; @@ -199,6 +327,18 @@ IndexKind index_kind_of(const torch::Tensor& edge_index) { } } +/// Call ``body`` with a value of the integer type that source indices of +/// ``kind`` take in the kernels: ``long`` for 64-bit indices and +/// ``std::uint32_t`` for 32-bit ones. +template +void with_index_type(IndexKind kind, const Body& body) { + if (kind == IndexKind::Bits64) { + body(long{}); + } else { + body(std::uint32_t{}); + } +} + Arguments build_arguments(const Payload& payload, const torch::Tensor& edge_vec, int channels, @@ -1763,6 +1903,1060 @@ void finish_energy_force(cudaStream_t stream, } } +// === Further message-passing blocks === + +/// The stream of high priority on which the operators run work beside the +/// current stream of ``device``, the same stream on every call: the caching +/// allocator keeps the memory that the work allocates in a pool of that +/// stream, which every later call then reuses. +c10::cuda::CUDAStream side_stream(c10::DeviceIndex device) { + static std::mutex mutex; + static std::map streams; + const std::lock_guard lock(mutex); + const auto known = streams.find(device); + if (known != streams.end()) { + return known->second; + } + return streams + .emplace(device, + at::cuda::getStreamFromPool(/*isHighPriority=*/true, device)) + .first->second; +} + +/// The border plan of a node set whose halo rows the further blocks of a +/// descriptor read (border_exchange.h), and the rows the operator evaluates; +/// a node set without a plan evaluates every row. +struct HaloPlan { + torch::Tensor send_nodes; + torch::Tensor swaps; + torch::Tensor communicator; + long owned = 0; + + /// Refresh the halo rows of a node feature from the ranks that own them. + void exchange(const torch::Tensor& rows) const { + if (swaps.defined()) { + deepmd::border_exchange(rows, send_nodes, swaps, communicator); + } + } + + /// Whether the swaps of the plan cross processes, whose messages the host + /// waits for, rather than copy the rows of a single process on the device. + bool crosses_processes() const { + return swaps.defined() && + deepmd::communicator_address(communicator, "border_exchange") != 0; + } + + /// As exchange, on the stream ``side`` once the current stream reaches + /// ``written``, so that the kernels the current stream runs meanwhile + /// overlap the transfers. The current stream then waits for the exchange. + void exchange_beside(const torch::Tensor& rows, + at::cuda::CUDAEvent& written, + const c10::cuda::CUDAStream& side) const { + written.block(side); + { + const c10::cuda::CUDAStreamGuard guard(side); + exchange(rows); + } + at::cuda::CUDAEvent exchanged; + exchanged.record(side); + exchanged.block(at::cuda::getCurrentCUDAStream()); + } + + /// Add the halo rows of a node quantity onto the rows of the atoms they + /// image, on the ranks that own them. + void accumulate(const torch::Tensor& rows) const { + if (swaps.defined()) { + deepmd::border_accumulate(rows, send_nodes, swaps, communicator); + } + } +}; + +// === Source gate of a bridged descriptor of several blocks === +// +// The envelope of an edge carries the leave-one-out gate of its source, the +// product of the switches of the other pairs of the source (Arguments:: +// source_gate). A canonical graph holds both directions of every bond, so +// the row of a node holds every pair of the node, and the totals of the +// switches of an owned node follow from its own row; those of a halo row +// arrive from its owner. + +constexpr int kGateThreads = 256; +constexpr int kGateWarps = kGateThreads / deepmd_dpa4c::kWarpSize; + +/// The switch of the pair of an entry of the row of ``row_node`` and the +/// slope of the switch with respect to the length; the length, the unit +/// vector and the vector of the entry are returned as well. +struct PairSwitch { + float weight; + float slope; + float radius; + float vector[3]; +}; + +template +__device__ __forceinline__ PairSwitch pair_switch(const Arguments& args, + long row_node, + long position) { + PairSwitch pair; + const float x = args.edge_vec[position * 3 + 0]; + const float y = args.edge_vec[position * 3 + 1]; + const float z = args.edge_vec[position * 3 + 2]; + pair.vector[0] = x; + pair.vector[1] = y; + pair.vector[2] = z; + // The regularized length of load_geometry, so that the switch of the + // totals is that of the edge scans. + const float square = x * x + y * y + z * z + args.eps * args.eps; + pair.radius = square * rsqrtf(square); + pair.weight = 1.0f; + pair.slope = 0.0f; + const long source = + static_cast(static_cast(args.edge_index)[position]); + const float contact = __ldg(args.contact_radius + args.atype[row_node]) + + __ldg(args.contact_radius + args.atype[source]); + if (pair.radius < args.f_outer * contact) { + const float t = deepmd_dpa4c::window_parameter( + __fdividef(pair.radius, contact), args.f_inner, args.inverse_f_width); + pair.weight = deepmd_dpa4c::bridging_switch(t); + pair.slope = __fdividef( + deepmd_dpa4c::bridging_switch_derivative(t, args.inverse_f_width), + contact); + } + return pair; +} + +/// The totals of the switches of the pairs of every owned node: the sum of +/// the logarithms of the nonzero switches and the number of zero ones. One +/// warp scans one row, and the lanes combine their partial totals in a fixed +/// order. +template +__global__ void __launch_bounds__(kGateThreads) + source_gate_kernel(const Arguments args, float2* totals) { + const long row = + static_cast(blockIdx.x) * kGateWarps + threadIdx.x / 32; + if (row >= args.node_count) { + return; + } + const int lane = threadIdx.x % 32; + const long node = args.node_begin + row; + float log_sum = 0.0f; + float frozen = 0.0f; + for (long position = args.destination_row_ptr[row] + lane; + position < args.destination_row_ptr[row + 1]; position += 32) { + const float weight = pair_switch(args, node, position).weight; + if (weight <= 0.0f) { + frozen += 1.0f; + } else { + log_sum += __logf(weight); + } + } +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + log_sum += __shfl_xor_sync(0xffffffffu, log_sum, offset); + frozen += __shfl_xor_sync(0xffffffffu, frozen, offset); + } + if (lane == 0) { + totals[node] = make_float2(log_sum, frozen); + } +} + +/// The slope of the switches under a source gate. The switch ``w`` of a pair +/// of node ``j`` enters the gate of every other edge that ``j`` emits, so with +/// the gate total ``A_j``, the sum over the edges of ``j`` of the envelope +/// cotangent times the envelope, the energy changes through those gates with +/// the length of the pair by ``(dw/dr / w) (A_j - a)``, where ``a`` is the +/// term of the edge along the pair itself. That term cancels the slope of the +/// switch in the envelope of the edge, which the edge scans therefore leave +/// out (radial_chain), so this pass adds ``(dw/dr / w) A_j`` to every edge of +/// ``j`` whose switch lies strictly between zero and one. One warp scans the +/// row of one owned node ``j``, whose entries are the pairs of ``j``, each read +/// as the edge ``j`` emits: the entry gains the force ``+g``, the row ``-g`` +/// and the virial ``-g (x) v``, which is attributed to ``j``; the lanes combine +/// the share of the row in a fixed order. +template +__global__ void __launch_bounds__(kGateThreads) + gate_closure_kernel(const Arguments args, + const float2* totals, + const float* gate_sums, + unsigned long long* force, + float* virial) { + const long row = + static_cast(blockIdx.x) * kGateWarps + threadIdx.x / 32; + if (row >= args.node_count) { + return; + } + const long node = args.node_begin + row; + if (!deepmd_dpa4c::has_window_pair(totals[node])) { + return; + } + const int lane = threadIdx.x % 32; + const float total = gate_sums[node]; + float share[12] = {}; + for (long position = args.destination_row_ptr[row] + lane; + position < args.destination_row_ptr[row + 1]; position += 32) { + const PairSwitch pair = pair_switch(args, node, position); + if (pair.weight <= 0.0f || pair.weight >= 1.0f) { + continue; + } + // The stored vector points from the entry to the row; the edge the row + // emits points the other way. + const float scale = + __fdividef(pair.slope, pair.weight) * total / pair.radius; + const long entry = static_cast( + static_cast(args.edge_index)[position]); + unsigned long long* const words = force + entry * deepmd_dpa4c::kForceWords; +#pragma unroll + for (int component = 0; component < 3; ++component) { + const float gradient = -scale * pair.vector[component]; + deepmd_dpa4c::check_force_range(gradient, words); + atomicAdd(words + component, deepmd_dpa4c::fixed_point(gradient)); + share[component] -= gradient; + } +#pragma unroll + for (int component = 0; component < 9; ++component) { + share[3 + component] -= + scale * pair.vector[component / 3] * pair.vector[component % 3]; + } + } +#pragma unroll + for (int component = 0; component < 12; ++component) { +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + share[component] += + __shfl_xor_sync(0xffffffffu, share[component], offset); + } + } + if (lane == 0) { + unsigned long long* const words = force + node * deepmd_dpa4c::kForceWords; +#pragma unroll + for (int component = 0; component < 3; ++component) { + deepmd_dpa4c::check_force_range(share[component], words); + atomicAdd(words + component, deepmd_dpa4c::fixed_point(share[component])); + } +#pragma unroll + for (int component = 0; component < 9; ++component) { + virial[node * 9 + component] += share[3 + component]; + } + } +} + +int gate_blocks(const Arguments& args) { + return static_cast((args.node_count + kGateWarps - 1) / kGateWarps); +} + +/// The switch totals of the owned rows of ``args`` into ``totals``. +void launch_source_gate(const Arguments& args, + float2* totals, + cudaStream_t stream) { + if (args.node_count == 0) { + return; + } + with_index_type(args.index_kind, [&](auto index) { + source_gate_kernel + <<>>(args, totals); + }); + DPA4C_CHECK_LAUNCH("dpa4c switch totals of the source gate"); +} + +/// The slope of the switches of the owned rows of ``args`` under a source +/// gate, onto the fixed-point forces and the virial of every node. +void launch_gate_closure(const Arguments& args, + const float2* totals, + const float* gate_sums, + unsigned long long* force, + float* virial, + cudaStream_t stream) { + if (args.node_count == 0) { + return; + } + with_index_type(args.index_kind, [&](auto index) { + gate_closure_kernel + <<>>( + args, totals, gate_sums, force, virial); + }); + DPA4C_CHECK_LAUNCH("dpa4c switch slope of the source gate"); +} + +/// The validated border plan of an energy-force evaluation. The send list, +/// the swaps and the communicator come together, for a descriptor of further +/// blocks; a plan with halo rows serves a single frame. +HaloPlan halo_plan(const char* op, + const std::optional& send_nodes, + const std::optional& swaps, + const std::optional& communicator, + long node_count, + long frame_count, + long block_count, + const torch::Tensor& n_local) { + const int given = static_cast(send_nodes.has_value()) + + static_cast(swaps.has_value()) + + static_cast(communicator.has_value()); + if (given == 0) { + return {torch::Tensor(), torch::Tensor(), torch::Tensor(), node_count}; + } + TORCH_CHECK(given == 3, op, + ": the send list, the swaps and the communicator of a border " + "plan are given together"); + TORCH_CHECK(block_count > 0, op, + ": a border plan refreshes the halo rows that further " + "message-passing blocks read, but the descriptor has one block"); + TORCH_CHECK(send_nodes->device() == n_local.device(), op, + ": the border send list must be on the graph's device"); + const long owned = deepmd::check_border_plan(*send_nodes, *swaps, + *communicator, node_count, op); + TORCH_CHECK(owned == node_count || frame_count == 1, op, + ": a border plan with halo rows serves a node set of one " + "frame, got ", + frame_count, " frames"); + at::_assert_async(n_local.sum() == owned, + "the halo plan's owned-node count must match n_local"); + return {*send_nodes, *swaps, *communicator, owned}; +} + +/// The further message-passing blocks of a call: their records, one row per +/// further block and none for a descriptor of one block, and the cutoff in Å +/// of every further block. +struct FurtherBlocks { + torch::Tensor records; + std::vector cutoffs; + + long count() const { return records.defined() ? records.size(0) : 0; } +}; + +__global__ void check_block_cutoff(const float* record, float cutoff) { + CUDA_KERNEL_ASSERT(record[0] == cutoff); +} + +/// The further blocks of ``blocks`` and ``block_rcut``, whose cutoffs must not +/// rise from block to block above ``rcut``, that of the first block. Without +/// the cutoffs, every block scans the edges of the first, whose messages +/// beyond its own cutoff vanish with its envelope. +FurtherBlocks further_blocks( + const char* op, + const std::optional& blocks, + const std::optional>& block_rcut, + double rcut) { + FurtherBlocks further{blocks.value_or(torch::Tensor()), {}}; + TORCH_CHECK(!further.records.defined() || further.records.dim() == 2, op, + ": the records of the further blocks must form a matrix, got ", + further.records.sizes()); + const long count = further.count(); + further.cutoffs = block_rcut.value_or(std::vector(count, rcut)); + TORCH_CHECK(static_cast(further.cutoffs.size()) == count, op, + ": block_rcut must hold the cutoff of every further block, one " + "per record of blocks; got ", + further.cutoffs.size(), " cutoff(s) for ", count, " record(s)"); + for (long b = 0; b < count; ++b) { + const double previous = b == 0 ? rcut : further.cutoffs[b - 1]; + TORCH_CHECK(further.cutoffs[b] > 0.0 && further.cutoffs[b] <= previous, op, + ": the cutoff of further block ", b + 1, + " must be positive and at most ", previous, + " Å, that of the block before; got ", further.cutoffs[b], " Å"); + } + if (count > 0 && block_rcut.has_value()) { + TORCH_CHECK( + further.records.is_cuda() && further.records.is_contiguous() && + further.records.scalar_type() == torch::kFloat32 && + further.records.get_device() == c10::cuda::current_device() && + further.records.size(1) > 0, + op, + ": block records must be a contiguous float32 matrix on " + "the graph's CUDA device"); + for (long b = 0; b < count; ++b) { + check_block_cutoff<<<1, 1, 0, at::cuda::getCurrentCUDAStream()>>>( + further.records.data_ptr() + b * further.records.size(1), + static_cast(further.cutoffs[b])); + } + DPA4C_CHECK_LAUNCH("dpa4c block cutoff validation"); + } + return further; +} + +/// A node buffer of a fused energy-force operator. With further blocks the +/// runs cover the owned rows alone, so a buffer that the epilogue reads for +/// every node starts cleared. +torch::Tensor node_buffer(long block_count, + at::IntArrayRef shape, + const torch::TensorOptions& options) { + return block_count > 0 ? torch::zeros(shape, options) + : torch::empty(shape, options); +} + +/// The launch of the first block of a fused energy-force operator over the run +/// of ``count`` rows from ``begin``, from ``payload``, the canonical payload of +/// the whole node set: the run writes its descriptor at ``descriptor`` and its +/// moments at ``state``, and reads the node types that the prologue of the +/// call scanned into ``words``. The row split of its scans, which sets their +/// summation order, follows from ``system_nodes``, the rows that the call +/// evaluates in all, so that every run of a tiled call sums alike. +Arguments first_block_run(Payload payload, + const torch::Tensor& edge_vec, + int channels, + const Dimensions& widths, + long system_nodes, + long begin, + long count, + float* descriptor, + float* state, + EvaluationWords* words) { + payload.destination_row_ptr = + payload.destination_row_ptr.slice(0, begin, begin + count + 1); + payload.node_begin = begin; + Arguments arguments = build_arguments(payload, edge_vec, channels, widths); + arguments.system_node_count = system_nodes; + arguments.descriptor = descriptor; + arguments.state_out = state; + arguments.type_mismatch = &words->node_types.type_mismatch; + arguments.largest_radius = &words->node_types.largest_radius; + arguments.type_present = present_types(arguments, &words->node_types); + return arguments; +} + +// === Edges of a further block === +// +// A further block reads the edges of the graph inside its own cutoff, which +// may lie below that of the graph: every message of an edge beyond it carries +// the envelope of the block, which vanishes there with its slope. A block of +// a smaller cutoff therefore scans a graph of its own, which holds the edges +// of every row inside the cutoff in the order of the row, so that its scans +// visit no edge whose messages vanish. + +constexpr int kSelectThreads = 256; +constexpr int kSelectWarps = kSelectThreads / deepmd_dpa4c::kWarpSize; + +/// A graph of compact rows: the row pointers, (rows + 1), the source of every +/// edge and its vector, (storage) and (storage, 3), whose storage may exceed +/// the edges of the rows. +struct EdgeGraph { + torch::Tensor row_ptr; + torch::Tensor source; + torch::Tensor edge_vec; +}; + +/// Whether an edge lies inside the cutoff whose square, widened by a relative +/// 1e-5, is ``bound``. The regularized length of block_geometry is at least +/// the length of the vector, so every edge that the envelope of the cutoff +/// reads inside it is kept, and the edges kept beyond it carry an envelope of +/// zero. +__device__ __forceinline__ bool inside_cutoff(const float* edge_vec, + long position, + float bound) { + const float x = edge_vec[position * 3 + 0]; + const float y = edge_vec[position * 3 + 1]; + const float z = edge_vec[position * 3 + 2]; + return x * x + y * y + z * z < bound; +} + +/// The number of edges of every row inside the cutoff, into +/// ``counts[row + 1]``. One warp counts one row. +__global__ void __launch_bounds__(kSelectThreads) + count_block_edges_kernel(const long* row_ptr, + const float* edge_vec, + long rows, + float bound, + long* counts) { + const long row = + static_cast(blockIdx.x) * kSelectWarps + threadIdx.x / 32; + if (row >= rows) { + return; + } + const int lane = threadIdx.x % 32; + int count = 0; + for (long position = row_ptr[row] + lane; position < row_ptr[row + 1]; + position += 32) { + count += inside_cutoff(edge_vec, position, bound) ? 1 : 0; + } +#pragma unroll + for (int offset = 16; offset > 0; offset >>= 1) { + count += __shfl_xor_sync(0xffffffffu, count, offset); + } + if (lane == 0) { + counts[row + 1] = count; + } +} + +/// The edges of every row inside the cutoff, in the order of the row, from +/// ``block_row_ptr[row]`` on. One warp moves one row, 32 edges at a time, each +/// kept edge to its rank among the kept edges before it. +template +__global__ void __launch_bounds__(kSelectThreads) + gather_block_edges_kernel(const long* row_ptr, + const index_t* source, + const float* edge_vec, + long rows, + float bound, + const long* block_row_ptr, + index_t* block_source, + float* block_vec) { + const long row = + static_cast(blockIdx.x) * kSelectWarps + threadIdx.x / 32; + if (row >= rows) { + return; + } + const int lane = threadIdx.x % 32; + const unsigned before = (1u << lane) - 1u; + const long end = row_ptr[row + 1]; + long target = block_row_ptr[row]; + for (long first = row_ptr[row]; first < end; first += 32) { + const long position = first + lane; + const bool keep = + position < end && inside_cutoff(edge_vec, position, bound); + const unsigned kept = __ballot_sync(0xffffffffu, keep); + if (keep) { + const long slot = target + __popc(kept & before); + block_source[slot] = source[position]; + block_vec[slot * 3 + 0] = edge_vec[position * 3 + 0]; + block_vec[slot * 3 + 1] = edge_vec[position * 3 + 1]; + block_vec[slot * 3 + 2] = edge_vec[position * 3 + 2]; + } + target += __popc(kept); + } +} + +/// The edges of ``graph`` inside ``cutoff`` in Å, in the storage of ``graph``. +EdgeGraph select_block_edges(const EdgeGraph& graph, + double cutoff, + cudaStream_t stream) { + const long rows = graph.row_ptr.numel() - 1; + const float bound = static_cast(cutoff * cutoff * (1.0 + 1e-5)); + auto counts = torch::zeros({rows + 1}, graph.row_ptr.options()); + EdgeGraph selected{torch::Tensor(), torch::empty_like(graph.source), + torch::empty_like(graph.edge_vec)}; + if (rows == 0) { + selected.row_ptr = counts; + return selected; + } + const int blocks = static_cast((rows + kSelectWarps - 1) / kSelectWarps); + count_block_edges_kernel<<>>( + graph.row_ptr.data_ptr(), graph.edge_vec.data_ptr(), rows, + bound, counts.data_ptr()); + DPA4C_CHECK_LAUNCH("dpa4c count of the edges of a further block"); + selected.row_ptr = counts.cumsum(0); + with_index_type(index_kind_of(graph.source), [&](auto index) { + using index_t = decltype(index); + gather_block_edges_kernel<<>>( + graph.row_ptr.data_ptr(), + static_cast(graph.source.data_ptr()), + graph.edge_vec.data_ptr(), rows, bound, + selected.row_ptr.data_ptr(), + static_cast(selected.source.data_ptr()), + selected.edge_vec.data_ptr()); + }); + DPA4C_CHECK_LAUNCH("dpa4c gather of the edges of a further block"); + return selected; +} + +// === Rows that read halo rows === +// +// On a node set whose halo rows arrive from other processes, an edge scan +// first visits the rows whose entries are all owned rows, which read nothing +// of the halo, while the halo rows are exchanged, and the other rows once the +// exchange completes. A canonical graph holds both directions of every bond, +// so the same rows serve the forward, which reads the source features of the +// entries, and the backward, which reads their destination cotangents. + +/// The rows of a run of ``count`` rows of a graph, ascending: those whose +/// entries are all owned (inner), then the others (border), each list in a +/// row of ``rows`` (2, count), and their numbers in ``counts`` (2), both on +/// the device. +struct RowSplit { + torch::Tensor rows; + torch::Tensor counts; +}; + +/// Whether every row of the run reads only owned rows, into ``inner``: one +/// warp checks the entries of one row. +template +__global__ void __launch_bounds__(kSelectThreads) + inner_rows_kernel(const long* row_ptr, + const index_t* source, + long rows, + long owned, + int* inner) { + const long row = + static_cast(blockIdx.x) * kSelectWarps + threadIdx.x / 32; + if (row >= rows) { + return; + } + const int lane = threadIdx.x % 32; + bool reads_halo = false; + for (long position = row_ptr[row] + lane; position < row_ptr[row + 1]; + position += 32) { + reads_halo |= static_cast(source[position]) >= owned; + } + const bool any = __any_sync(0xffffffffu, reads_halo); + if (lane == 0) { + inner[row] = any ? 0 : 1; + } +} + +/// Every row of the run into its list, at the rank the inclusive counts +/// ``inner_rank`` give it, and the numbers of both lists. +__global__ void split_rows_kernel(const int* inner, + const int* inner_rank, + long rows, + int* lists, + int* counts) { + const long row = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (row >= rows) { + return; + } + const int before = inner_rank[row] - inner[row]; + if (inner[row] != 0) { + lists[before] = static_cast(row); + } else { + lists[rows + row - before] = static_cast(row); + } + if (row == rows - 1) { + counts[0] = inner_rank[row]; + counts[1] = static_cast(rows) - inner_rank[row]; + } +} + +/// The inner and border rows of the run of ``count`` rows from ``begin`` of +/// ``graph`` on a node set of ``owned`` owned rows. +RowSplit split_rows(const EdgeGraph& graph, + long begin, + long count, + long owned, + cudaStream_t stream) { + const auto i32 = graph.row_ptr.options().dtype(torch::kInt32); + auto inner = torch::empty({count}, i32); + RowSplit split{torch::empty({2, count}, i32), torch::empty({2}, i32)}; + const int blocks = + static_cast((count + kSelectWarps - 1) / kSelectWarps); + const long* row_ptr = graph.row_ptr.data_ptr() + begin; + with_index_type(index_kind_of(graph.source), [&](auto index) { + using index_t = decltype(index); + inner_rows_kernel<<>>( + row_ptr, static_cast(graph.source.data_ptr()), count, + owned, inner.data_ptr()); + }); + DPA4C_CHECK_LAUNCH("dpa4c inner rows of a further block"); + const auto rank = inner.cumsum(0, torch::kInt32); + split_rows_kernel<<((count + 255) / 256), 256, 0, stream>>>( + inner.data_ptr(), rank.data_ptr(), count, + split.rows.data_ptr(), split.counts.data_ptr()); + DPA4C_CHECK_LAUNCH("dpa4c row split of a further block"); + return split; +} + +/// What the descriptor of the last block feeds. ``run(begin, count, rows)`` +/// replaces the descriptor of the ``count`` owned rows from ``begin``, held at +/// ``rows``, by its cotangent: the energy fitting reads the descriptor of a run +/// alone, so every run completes as soon as its readout is done. ``all()``, +/// when set, replaces the descriptor of every owned row at once instead, after +/// the readout of the last run: the energy of a long-range module couples the +/// charges of all nodes, so no cotangent exists before every charge does, and +/// the moments and the transport of the last block are kept for every node +/// until then. The descriptor is then a node buffer, whose run rows the launch +/// of each run addresses. +struct BlockHead { + std::function run; + std::function all; +}; + +/// What the further blocks of a descriptor share with the run loop of the +/// fused energy-force operator ``op``, which names it in their diagnostics. +struct BlockPass { + const char* op; + const torch::Tensor& records; + // Cutoff in Å of the first block, that of the graph, and of every further + // block, one per record and none above the one before. + double rcut; + const std::vector& block_rcut; + // The graph of the first block, its row pointers over the whole node set. + const EdgeGraph& graph; + const HaloPlan& halo; + int channels; + int lmax; + bool has_spin; + // Whether the descriptor has a bridging window, whose switches gate the + // edges of every source (Arguments::source_gate). + bool bridged; + const Dimensions& widths; + long node_count; + long run; + const BlockHead& head; + // The descriptor buffer of the operator, a run buffer or, under a deferred + // head, a node buffer, and the run buffer of the moment gradient. + const torch::Tensor& descriptor; + const torch::Tensor& state; + // Node buffer of the operator. + const torch::Tensor& spin_gradient; + unsigned long long* force; + cudaStream_t stream; +}; + +/// The descriptor of several blocks (block_launch.h) with what it feeds and +/// its force, over the owned rows of the node set in runs of ``pass.run`` +/// rows. +/// +/// The forward evaluates the first block of every run, keeping its moments +/// for the whole node set, and the node maps of the second block. Block after +/// block, it then refreshes the source features of the halo rows and +/// evaluates the edge scan and the readout of every run, followed by the node +/// maps of the next block or, for the last block, by the head (BlockHead), +/// which replaces the descriptor by its cotangent, the readout VJP and the +/// destination cotangents of the block: in the same run, or, under a deferred +/// head, in a second pass over the runs once the head has formed the +/// cotangent of every owned row. The launch of each run addresses the rows of +/// the descriptor buffer that the run fills. +/// The backward visits the blocks in reverse: it refreshes the destination +/// cotangents of the halo rows, scans the source rows of every run, and pulls +/// the source cotangent back through the node maps and the readout of the +/// block before, into the destination cotangents of that block or, for the +/// first block, into the moment gradient from which its edge backward +/// assembles the force. The edge scans of a further block whose cutoff lies +/// below that of the block before read the edges inside it alone, selected +/// once from the edges of the block before. +/// +/// A bridged descriptor gates the edges of every source by the switches of +/// its other pairs: the switch totals of every node precede the first block, +/// every edge backward adds the envelope cotangents times the envelopes of the +/// edges of a gated source to its gate total, and once the totals of the halo +/// rows have reached their owners, a last pass adds the slope of the +/// switches through the gates. +/// +/// ``first_arguments(begin, count)`` returns the launch of the first block +/// over a run, and ``attach_force(arguments, begin, count)`` adds the force +/// assembly to it. Returns the virial of the edges of the further blocks and +/// of the gates, attributed to the node that emits each, (node_count, 9). +template +torch::Tensor evaluate_further_blocks(const BlockPass& pass, + const FirstArguments& launch_arguments, + const AttachForce& attach_force) { + const BlockWidths sizes = + block_widths(pass.channels, pass.lmax, pass.has_spin); + const torch::Tensor& records = pass.records; + TORCH_CHECK(records.device() == pass.descriptor.device() && + records.scalar_type() == torch::kFloat32 && + records.dim() == 2 && records.size(1) == sizes.record && + records.is_contiguous(), + pass.op, + ": the records of the further blocks must be a contiguous " + "float32 matrix of ", + sizes.record, " columns on the device of the graph, got ", + records.sizes()); + const long block_count = records.size(0); + const long node_count = pass.node_count; + const long owned = pass.halo.owned; + const long run = pass.run; + const long state_width = pass.widths.moment_width + 2; + const int channels = pass.channels; + const cudaStream_t stream = pass.stream; + const auto f32 = pass.descriptor.options(); + const auto i64 = f32.dtype(torch::kInt64); + float* const state = pass.state.data_ptr(); + const bool deferred = static_cast(pass.head.all); + + // === Source gate === + // The switch totals of the owned rows, and of the halo rows from their + // owners, which every launch of the first block and of the further blocks + // reads. + torch::Tensor gate_totals; + if (pass.bridged) { + gate_totals = torch::zeros({node_count, 2}, f32); + launch_source_gate(launch_arguments(0, owned), + reinterpret_cast(gate_totals.data_ptr()), + stream); + pass.halo.exchange(gate_totals); + } + const float2* const source_gate = + pass.bridged + ? reinterpret_cast(gate_totals.data_ptr()) + : nullptr; + const auto first_arguments = [&](long begin, long count) { + Arguments arguments = launch_arguments(begin, count); + arguments.source_gate = source_gate; + return arguments; + }; + + // === Edges of every further block === + std::vector graphs; + graphs.reserve(block_count); + for (long b = 0; b < block_count; ++b) { + const double previous = b == 0 ? pass.rcut : pass.block_rcut[b - 1]; + const EdgeGraph& before = b == 0 ? pass.graph : graphs.back(); + graphs.push_back( + pass.block_rcut[b] < previous + ? select_block_edges(before, pass.block_rcut[b], stream) + : before); + } + // The launch of the edge scans of further block ``b`` over a run: that of + // the first block on the edges of the block. + const auto block_edges = [&](long b, long begin, long count) { + Arguments arguments = first_arguments(begin, count); + const EdgeGraph& graph = graphs[b]; + arguments.destination_row_ptr = graph.row_ptr.data_ptr() + begin; + arguments.edge_index = graph.source.data_ptr(); + arguments.edge_vec = graph.edge_vec.data_ptr(); + return arguments; + }; + // A node set whose halo rows other processes deliver splits the rows of + // its first run, on the edges of every block, into the rows that read no + // halo row, which the scans of the run visit while the halo rows of the + // block are exchanged, and the others, which they visit afterwards. + const bool overlap = pass.halo.crosses_processes() && owned > 0; + std::vector splits; + // The side stream carries every exchange of the call. + const c10::cuda::CUDAStream side = + overlap ? side_stream(pass.descriptor.get_device()) + : at::cuda::getCurrentCUDAStream(); + if (overlap) { + const long count = std::min(run, owned); + splits.reserve(block_count); + for (long b = 0; b < block_count; ++b) { + splits.push_back(b > 0 && graphs[b].row_ptr.is_same(graphs[b - 1].row_ptr) + ? splits.back() + : split_rows(graphs[b], 0, count, owned, stream)); + } + } + // The edge scan ``stage`` of block ``b`` over a run, and the exchange of + // the halo rows of ``exchanged`` that the scans of the block read, before + // the scan of the first run: beside the inner rows of that run when the + // rows cross processes. + const auto scan_run = [&](BlockStage stage, const BlockArguments& block, + long b, long begin, + const torch::Tensor& exchanged) { + if (begin != 0) { + dispatch_block(channels, stage, block, stream); + return; + } + if (!overlap) { + pass.halo.exchange(exchanged); + dispatch_block(channels, stage, block, stream); + return; + } + at::cuda::CUDAEvent written; + written.record(at::cuda::getCurrentCUDAStream()); + for (int part = 0; part < 2; ++part) { + BlockArguments rows = block; + rows.scan_rows = splits[b].rows[part].data_ptr(); + rows.scan_row_count = splits[b].counts.data_ptr() + part; + dispatch_block(channels, stage, rows, stream); + if (part == 0) { + pass.halo.exchange_beside(exchanged, written, side); + } + } + }; + // A node set without owned rows has no runs, and still takes part in the + // exchange of every block, whose swaps may forward rows of other ranks. + const auto exchange_without_runs = [&](const torch::Tensor& exchanged) { + if (owned == 0) { + pass.halo.exchange(exchanged); + } + }; + + // === Node buffers === + // The moments of the first block and of every block before the last, and + // the transport of every such block, which the backward reads again; under + // a deferred head those of the last block as well, which its readout VJP + // and its destination cotangents read after the head. + const long kept = deferred ? block_count : block_count - 1; + auto first_state = torch::empty({node_count, state_width}, f32); + auto states = torch::empty({kept, node_count, state_width}, f32); + auto transports = torch::empty({kept, node_count, sizes.transport}, f32); + auto sources = torch::empty({block_count, node_count, sizes.source}, f32); + auto centers = torch::empty({block_count, node_count, kBlockHeads}, f32); + auto divisors = torch::empty({node_count, 2}, f32); + // The edges of a block read the destination cotangents of every node while + // the block before forms its own, so two buffers alternate. + auto cotangents = torch::empty({2, node_count, sizes.cotangent}, f32); + auto center_gradient = torch::empty({node_count, kBlockHeads}, f32); + auto carried = torch::empty({node_count, state_width}, f32); + auto block_virial = torch::zeros({node_count, 9}, f32); + // The gate totals of every node: those of the first block in fixed point, + // those of the further blocks, whose backward scans the rows of the sources, + // as row sums. + torch::Tensor gate_fixed; + torch::Tensor gate_rows; + if (pass.bridged) { + gate_fixed = torch::zeros({node_count}, i64); + gate_rows = torch::zeros({node_count}, f32); + } + // === Run buffers === + auto transport = torch::empty({run, sizes.transport}, f32); + auto source_gradient = torch::empty({run, sizes.source}, f32); + auto keys_gradient = torch::empty({run, state_width}, f32); + auto map_cotangent = torch::empty({run, sizes.node}, f32); + auto onsite = pass.has_spin ? torch::empty({run, 3}, f32) : torch::Tensor(); + + const auto rows = [](const torch::Tensor& buffer, long begin) { + return buffer.data_ptr() + begin * buffer.size(-1); + }; + // The launch of further block ``b`` over the run of ``edges``. + const auto block_arguments = [&](const Arguments& edges, long b) { + BlockArguments block; + block.edges = edges; + block.record = records[b].data_ptr(); + block.first_state = first_state.data_ptr(); + block.previous_state = b == 0 ? first_state.data_ptr() + : states[b - 1].data_ptr(); + block.sources = sources[b].data_ptr(); + block.centers = centers[b].data_ptr(); + block.divisors = divisors.data_ptr(); + block.cotangents = cotangents[b % 2].data_ptr(); + block.carried = carried.data_ptr(); + block.center_gradient = rows(center_gradient, edges.node_begin); + return block; + }; + // Every readout VJP of a run adds the on-site magnetic gradient of its + // invariants. + const auto node_backward = [&](Arguments node, long begin, long count) { + if (pass.has_spin) { + node.spin_gradient = onsite.data_ptr(); + } + dispatch_first_stage(channels, FirstStage::NodeBackward, node, stream); + if (pass.has_spin) { + pass.spin_gradient.narrow(0, begin, count) + .add_(onsite.narrow(0, 0, count)); + } + }; + + // The launch of further block ``b`` over the run of ``count`` rows from + // ``begin``, which writes the moments and the transport of the block to + // the node rows of the run, or, for the last block of a head that completes + // each run in turn, to run buffers. + const auto further_run = [&](long b, long begin, long count) { + Arguments edges = block_edges(b, begin, count); + BlockArguments block = block_arguments(edges, b); + const bool buffered = b + 1 == block_count && !deferred; + block.state_out = buffered ? state : rows(states[b], begin); + block.transport = + buffered ? transport.data_ptr() : rows(transports[b], begin); + return std::make_pair(edges, block); + }; + // The readout VJP of the last block over a run, from the cotangent that the + // head left in the descriptor rows of the run, and the destination + // cotangents of the block, which its backward reads. + const auto finish_last_run = [&](Arguments edges, BlockArguments block, + long begin, long count) { + edges.descriptor_gradient = edges.descriptor; + edges.state = block.state_out; + edges.moment_gradient = state; + node_backward(edges, begin, count); + block.moment_gradient = state; + block.accumulate_carried = false; + dispatch_block(channels, BlockStage::Cotangents, block, stream); + }; + + // === Forward: the first block and the node maps of the second === + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + Arguments first = first_arguments(begin, count); + first.state_out = rows(first_state, begin); + dispatch(channels, false, first, stream); + BlockArguments maps = block_arguments(first, 0); + maps.descriptor = first.descriptor; + dispatch_block(channels, BlockStage::Maps, maps, stream); + } + + // === Forward: the further blocks === + for (long b = 0; b < block_count; ++b) { + const bool last = b + 1 == block_count; + exchange_without_runs(sources[b]); + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + auto [edges, block] = further_run(b, begin, count); + scan_run(BlockStage::Forward, block, b, begin, sources[b]); + edges.state_out = block.state_out; + edges.divisors = rows(divisors, begin); + dispatch_first_stage(channels, FirstStage::Readout, edges, stream); + if (!last) { + BlockArguments maps = block_arguments(edges, b + 1); + maps.descriptor = edges.descriptor; + dispatch_block(channels, BlockStage::Maps, maps, stream); + continue; + } + if (deferred) { + continue; + } + // The cotangent replaces the descriptor, which the run no longer needs. + pass.head.run(begin, count, edges.descriptor); + finish_last_run(edges, block, begin, count); + } + if (last && deferred) { + pass.head.all(); + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + auto [edges, block] = further_run(b, begin, count); + edges.state_out = block.state_out; + edges.divisors = rows(divisors, begin); + finish_last_run(edges, block, begin, count); + } + } + } + + // === Backward: the further blocks in reverse, then the first block === + for (long b = block_count - 1; b >= 0; --b) { + const torch::Tensor input = b == 0 ? first_state : states[b - 1]; + exchange_without_runs(cotangents[b % 2]); + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + Arguments edges = block_edges(b, begin, count); + edges.force = pass.force; + BlockArguments block = block_arguments(edges, b); + block.source_gradient = source_gradient.data_ptr(); + block.source_virial = rows(block_virial, begin); + if (pass.bridged) { + block.gate_sums = gate_rows.data_ptr(); + } + scan_run(BlockStage::Backward, block, b, begin, cotangents[b % 2]); + + // The invariants of the block before, which the node maps of the + // block read, then their cotangent in their place. + edges.state_out = rows(input, begin); + edges.divisors = rows(divisors, begin); + dispatch_first_stage(channels, FirstStage::Readout, edges, stream); + block.descriptor = edges.descriptor; + block.descriptor_gradient = edges.descriptor; + block.keys_gradient = keys_gradient.data_ptr(); + block.map_cotangent = map_cotangent.data_ptr(); + dispatch_block(channels, BlockStage::MapBackward, block, stream); + edges.descriptor_gradient = edges.descriptor; + edges.state = rows(input, begin); + edges.moment_gradient = state; + node_backward(edges, begin, count); + auto gradient = pass.state.narrow(0, 0, count); + gradient.add_(keys_gradient.narrow(0, 0, count)); + if (b > 0) { + BlockArguments before = block_arguments(edges, b - 1); + before.moment_gradient = state; + before.transport = rows(transports[b - 1], begin); + before.accumulate_carried = true; + dispatch_block(channels, BlockStage::Cotangents, before, stream); + continue; + } + gradient.add_(carried.narrow(0, begin, count)); + Arguments first = first_arguments(begin, count); + first.moment_gradient = state; + attach_force(first, begin, count); + if (pass.bridged) { + first.gate_sums = reinterpret_cast( + gate_fixed.data_ptr()); + } + dispatch_first_stage(channels, FirstStage::EdgeBackward, first, stream); + } + } + + // === Slope of the switches through the gates === + if (pass.bridged) { + auto gate_sums = + gate_fixed.to(torch::kFloat64) + .mul_(1.0 / static_cast(deepmd_dpa4c::kForceFixedScale)) + .add_(gate_rows) + .to(torch::kFloat32) + .reshape({node_count, 1}) + .contiguous(); + pass.halo.accumulate(gate_sums); + launch_gate_closure(first_arguments(0, owned), source_gate, + gate_sums.data_ptr(), pass.force, + block_virial.data_ptr(), stream); + } + return block_virial; +} + } // namespace // Energy, force and virial of one compressed inference step, evaluated over @@ -1798,7 +2992,7 @@ void finish_energy_force(cudaStream_t stream, // fixed-point force totals, and marks its frame like a non-finite total (see // kForceFixedLimit for the scope of the check). // -// Every reduction has a fixed order for a given node count and kernel +// Every reduction has a fixed order for a given graph and kernel // configuration, so an evaluation is reproducible bit for bit on one device; // the configuration follows from the device, so another device may differ in // the last bits. @@ -1858,7 +3052,12 @@ dpa4c_canonical_compress_energy_force( int64_t act, int64_t tile, torch::Tensor pair_table, - std::optional> fitting_routes) { + std::optional> fitting_routes, + std::optional blocks, + std::optional halo_send, + std::optional halo_swaps, + std::optional communicator, + std::optional> block_rcut) { const bool atom_virial = check_energy_force_inputs( "dpa4c_canonical_compress_energy_force", edge_vec, source, destination_row_ptr, source_row_ptr, source_order, n_node, n_local, atype, @@ -1870,6 +3069,16 @@ dpa4c_canonical_compress_energy_force( const Dimensions widths = profile_dimensions(channels, static_cast(lmax), has_spin); const long frame_count = n_node.size(0); + const FurtherBlocks further = further_blocks( + "dpa4c_canonical_compress_energy_force", blocks, block_rcut, rcut); + const long block_count = further.count(); + const HaloPlan halo = + halo_plan("dpa4c_canonical_compress_energy_force", halo_send, halo_swaps, + communicator, node_count, frame_count, block_count, n_local); + // A node set with halo rows evaluates its owned rows: the halo rows carry + // no edges, and every feature of theirs that an edge reads arrives from the + // rank that owns them. + const long owned = halo.owned; const auto f32 = edge_vec.options().dtype(torch::kFloat32); const auto f64 = edge_vec.options().dtype(torch::kFloat64); const auto i64 = edge_vec.options().dtype(torch::kInt64); @@ -1888,21 +3097,24 @@ dpa4c_canonical_compress_energy_force( auto mask = torch::empty({node_count}, edge_vec.options().dtype(torch::kInt32)); - auto raw_energy = torch::empty({node_count}, f64); + // With further blocks the runs cover the owned rows alone, and every node + // backward adds its on-site magnetic gradient, so the node buffers the + // epilogue reads start cleared. + auto raw_energy = node_buffer(block_count, {node_count}, f64); auto seed = torch::empty({node_count}, f64); auto node_type = torch::empty({node_count}, i64); auto force_fixed = torch::empty({node_count, kForceWords}, i64); - auto node_virial = torch::empty({node_count, 9}, f32); + auto node_virial = node_buffer(block_count, {node_count, 9}, f32); // The on-site magnetic gradient is node local, so a run writes only its own // rows. The neighbour part belongs to source nodes that other runs own and // accumulates in fixed point like the force. - auto spin_gradient = - has_spin ? torch::empty({node_count, 3}, f32) : torch::Tensor(); + auto spin_gradient = has_spin ? node_buffer(block_count, {node_count, 3}, f32) + : torch::Tensor(); auto spin_fixed = has_spin ? torch::empty({node_count, kForceWords}, i64) : torch::Tensor(); auto edge_gradient = atom_virial ? torch::empty_like(edge_vec_float) : torch::Tensor(); - const int blocks = epilogue_blocks(node_count); + const int blocks_of_epilogue = epilogue_blocks(node_count); auto words = torch::zeros({static_cast(sizeof(EvaluationWords) / sizeof(int))}, edge_vec.options().dtype(torch::kInt32)); @@ -1916,7 +3128,8 @@ dpa4c_canonical_compress_energy_force( } const torch::Tensor frame_row_ptr = frame_count > 1 ? frame_row_pointer(n_node) : torch::Tensor(); - energy_force_prologue_kernel<<>>( + energy_force_prologue_kernel<<>>( node_count, frame_count, n_local.data_ptr(), frame_count > 1 ? frame_row_ptr.data_ptr() : nullptr, atype.data_ptr(), node_type.data_ptr(), @@ -1933,73 +3146,59 @@ dpa4c_canonical_compress_energy_force( TORCH_CHECK(plan.n_layer > 0 && ws[0].size(0) == widths.output_width, "dpa4c_canonical_compress_energy_force: first fitting weight " "does not match the descriptor width"); - const long run = tile > 0 - ? std::max(1, std::min(tile, node_count)) - : node_count; + const long run = tile > 0 ? std::max(1, std::min(tile, owned)) + : std::max(1, owned); auto descriptor = torch::empty({run, widths.output_width}, f32); auto state = torch::empty({run, widths.moment_width + 2}, f32); const FittingNetwork fitting{plan, ws, bs, resnets, w_head, b_head, bias_atom_e, act}; - const FittingRuns runs(stream, fitting, run, node_count, - std::move(fitting_routes), f32); + const FittingRuns runs(stream, fitting, run, owned, std::move(fitting_routes), + f32); auto empty_index = torch::empty({0}, source.options()); auto empty_mask = torch::empty({0}, edge_vec.options().dtype(torch::kBool)); - for (long begin = 0; begin < node_count; begin += run) { - const long count = std::min(run, node_count - begin); - const Payload payload{ - source, - empty_mask, - empty_index, - destination_row_ptr.slice(0, begin, begin + count + 1), - node_type, - table, - basis_table, - basis_matrix, - pair_film, - pair_mixing, - type_embedding, - readout_matrices, - coupling_meta, - coupling_entry, - coupling_value, - output_mean, - output_inv_std, - spin, - spin_pair, - spin_type, - contact_radius, - true, - lmax, - table_stride, - table_max, - rcut, - eps, - degree_floor, - f_inner, - f_outer, - begin}; - Arguments arguments = - build_arguments(payload, edge_vec_float, channels, widths); - arguments.system_node_count = node_count; - arguments.descriptor = descriptor.data_ptr(); - arguments.state_out = state.data_ptr(); - arguments.type_mismatch = &evaluation_words->node_types.type_mismatch; - arguments.largest_radius = &evaluation_words->node_types.largest_radius; - arguments.type_present = - present_types(arguments, &evaluation_words->node_types); - dispatch(channels, false, arguments, stream); - - // The cotangent replaces the descriptor, which the run no longer needs. - runs.output_and_cotangent( - stream, begin, count, descriptor.data_ptr(), - descriptor.data_ptr(), widths.output_width, - node_type.data_ptr() + begin, seed.data_ptr() + begin, - raw_energy.data_ptr() + begin); - - arguments.descriptor_gradient = descriptor.data_ptr(); - arguments.state = state.data_ptr(); - arguments.moment_gradient = state.data_ptr(); + const Payload payload{source, + empty_mask, + empty_index, + destination_row_ptr, + node_type, + table, + basis_table, + basis_matrix, + pair_film, + pair_mixing, + type_embedding, + readout_matrices, + coupling_meta, + coupling_entry, + coupling_value, + output_mean, + output_inv_std, + spin, + spin_pair, + spin_type, + contact_radius, + true, + lmax, + table_stride, + table_max, + rcut, + eps, + degree_floor, + f_inner, + f_outer}; + // The launch bundle of the first block over the run of ``count`` owned rows + // from ``begin``, into the run buffers. + const auto first_arguments = [&](long begin, long count) { + return first_block_run(payload, edge_vec_float, channels, widths, owned, + begin, count, descriptor.data_ptr(), + state.data_ptr(), evaluation_words); + }; + // The force assembly of the edge backward of the first block over a run, + // and the analytical pair term: the fitting forward has assigned the energy + // rows of the run, and the seed is the cotangent the fitting backward + // consumed. + const auto attach_force = [&](Arguments& arguments, long begin, long count) { arguments.force = reinterpret_cast(force_fixed.data_ptr()); arguments.node_virial = node_virial.data_ptr() + begin * 9; @@ -2013,26 +3212,85 @@ dpa4c_canonical_compress_energy_force( } // Only the final run reaches the reserved edge slots; its row pointer ends // at the last physical edge, which is exactly where the padding begins. - arguments.clear_padding = begin + count == node_count; + arguments.clear_padding = begin + count == owned; if (pair_table.numel() != 0) { - // The fitting forward has assigned the energy rows of this run, and the - // seed is the cotangent the fitting backward just consumed. attach_pair_term(arguments, pair_table, edge_vec.device(), seed.data_ptr() + begin, raw_energy.data_ptr() + begin); } - dispatch(channels, true, arguments, stream); + }; + + torch::Tensor block_virial; + if (block_count > 0) { + const EdgeGraph graph{destination_row_ptr, source, edge_vec_float}; + // The energy fitting of each run, whose cotangent replaces the descriptor. + const auto energy_fitting = [&](long begin, long count, float* rows) { + runs.output_and_cotangent( + stream, begin, count, rows, rows, widths.output_width, + node_type.data_ptr() + begin, seed.data_ptr() + begin, + raw_energy.data_ptr() + begin); + }; + const BlockHead head{energy_fitting, nullptr}; + const BlockPass pass{ + "dpa4c_canonical_compress_energy_force", + further.records, + rcut, + further.cutoffs, + graph, + halo, + channels, + static_cast(lmax), + has_spin, + f_outer > f_inner, + widths, + node_count, + run, + head, + descriptor, + state, + spin_gradient, + reinterpret_cast(force_fixed.data_ptr()), + stream}; + block_virial = evaluate_further_blocks(pass, first_arguments, attach_force); + } else { + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + Arguments arguments = first_arguments(begin, count); + dispatch(channels, false, arguments, stream); + + // The cotangent replaces the descriptor, which the run no longer needs. + runs.output_and_cotangent( + stream, begin, count, descriptor.data_ptr(), + descriptor.data_ptr(), widths.output_width, + node_type.data_ptr() + begin, seed.data_ptr() + begin, + raw_energy.data_ptr() + begin); + + arguments.descriptor_gradient = descriptor.data_ptr(); + arguments.state = state.data_ptr(); + arguments.moment_gradient = state.data_ptr(); + attach_force(arguments, begin, count); + dispatch(channels, true, arguments, stream); + } } + // The further blocks attribute the virial of every edge to the node that + // emits it, its source, which is how the per-atom virial attributes it, so + // the frame virial and the per-atom virial take it as it is. + if (block_virial.defined()) { + node_virial.add_(block_virial); + } const EpilogueInputs step{n_node, frame_row_ptr, force_fixed, raw_energy, seed, node_virial, evaluation_words}; const SpinTerms spin_terms{spin_fixed, spin_gradient, force_mag}; const SourceVirialTerms source_terms{edge_gradient, edge_vec_float, source_row_ptr, source_order}; - finish_energy_force(stream, node_count, blocks, step, + finish_energy_force(stream, node_count, blocks_of_epilogue, step, has_spin ? &spin_terms : nullptr, atom_virial ? &source_terms : nullptr, nullptr, energy, atom_energy, force, virial, atom_virial_output); + if (block_virial.defined() && atom_virial) { + atom_virial_output.add_(block_virial.reshape({node_count, 3, 3})); + } return {energy, atom_energy, force, virial, atom_virial_output, force_mag, mask}; } @@ -2064,6 +3322,16 @@ dpa4c_canonical_compress_energy_force( // epilogue adds the energies, the forces at fixed charges and the per-node // virials of the long range. // +// A descriptor of several message-passing blocks (``blocks`` and +// ``block_rcut`` as in dpa4c_canonical_compress_energy_force) evaluates its +// blocks through evaluate_further_blocks, whose last block feeds the charges, +// the long range and the cotangent of the descriptor as one deferred head +// over the owned nodes; the backward of the blocks then assembles the force. +// A node set of one domain of a decomposed frame refreshes its halo rows +// through the border plan of ``halo_send`` and ``halo_swaps``, whose messages +// travel on the communicator of the long range, and evaluates its owned nodes +// alone, as that operator does. +// // The charge network has one channel and the layout of an eligible energy // fitting; its per-type bias is ``charge_bias``. ``coord``, ``total_charge``, // ``box``, ``coefficient``, ``communicator``, ``kernel``, ``channel``, @@ -2137,7 +3405,11 @@ dpa4c_canonical_compress_long_range_energy_force( int64_t order, double spacing, std::optional> fitting_routes, - std::optional> charge_fitting_routes) { + std::optional> charge_fitting_routes, + std::optional blocks, + std::optional halo_send, + std::optional halo_swaps, + std::optional> block_rcut) { constexpr const char* kOp = "dpa4c_canonical_compress_long_range_energy_force"; const bool atom_virial = check_energy_force_inputs( @@ -2157,6 +3429,16 @@ dpa4c_canonical_compress_long_range_energy_force( const Dimensions widths = profile_dimensions(channels, static_cast(lmax), /*has_spin=*/false); const long frame_count = n_node.size(0); + const FurtherBlocks further = further_blocks(kOp, blocks, block_rcut, rcut); + const long block_count = further.count(); + // The halo exchange of the further blocks travels on the communicator of + // the long range. + const HaloPlan halo = halo_plan( + kOp, halo_send, halo_swaps, + halo_send.has_value() ? std::optional(communicator) + : std::nullopt, + node_count, frame_count, block_count, n_local); + const long owned = halo.owned; const auto f32 = edge_vec.options().dtype(torch::kFloat32); const auto f64 = edge_vec.options().dtype(torch::kFloat64); const auto i64 = edge_vec.options().dtype(torch::kInt64); @@ -2178,16 +3460,16 @@ dpa4c_canonical_compress_long_range_energy_force( return {energy, atom_energy, force, virial, atom_virial_output, mask}; } - auto raw_energy = torch::empty({node_count}, f64); + auto raw_energy = node_buffer(block_count, {node_count}, f64); auto seed = torch::empty({node_count}, f64); auto charged = torch::empty({node_count}, edge_vec.options().dtype(torch::kBool)); auto node_type = torch::empty({node_count}, i64); auto force_fixed = torch::empty({node_count, kForceWords}, i64); - auto node_virial = torch::empty({node_count, 9}, f32); + auto node_virial = node_buffer(block_count, {node_count, 9}, f32); auto edge_gradient = atom_virial ? torch::empty_like(edge_vec_float) : torch::Tensor(); - const int blocks = epilogue_blocks(node_count); + const int epilogue = epilogue_blocks(node_count); auto words = torch::zeros({static_cast(sizeof(EvaluationWords) / sizeof(int))}, edge_vec.options().dtype(torch::kInt32)); @@ -2195,7 +3477,7 @@ dpa4c_canonical_compress_long_range_energy_force( reinterpret_cast(words.data_ptr()); const torch::Tensor frame_row_ptr = frame_count > 1 ? frame_row_pointer(n_node) : torch::Tensor(); - energy_force_prologue_kernel<<>>( + energy_force_prologue_kernel<<>>( node_count, frame_count, n_local.data_ptr(), frame_count > 1 ? frame_row_ptr.data_ptr() : nullptr, atype.data_ptr(), node_type.data_ptr(), @@ -2220,9 +3502,15 @@ dpa4c_canonical_compress_long_range_energy_force( ": the charge network must have a scalar head and one bias per " "type, as the energy fitting has"); - // === Step 1. Descriptor and moment state of every node === - auto descriptor = torch::empty({node_count, widths.output_width}, f32); - auto state = torch::empty({node_count, widths.moment_width + 2}, f32); + // The descriptor of every node, and the moment state of every node or, with + // further blocks, which keep their moments themselves, the moment gradient + // of a run. + const long run = tile > 0 ? std::max(1, std::min(tile, owned)) + : std::max(1, owned); + const long width = widths.output_width; + auto descriptor = torch::empty({node_count, width}, f32); + auto state = torch::empty( + {block_count > 0 ? run : node_count, widths.moment_width + 2}, f32); auto empty_index = torch::empty({0}, source.options()); auto empty_mask = torch::empty({0}, edge_vec.options().dtype(torch::kBool)); const Payload payload{source, @@ -2254,108 +3542,208 @@ dpa4c_canonical_compress_long_range_energy_force( eps, degree_floor, f_inner, - f_outer, - 0}; - Arguments arguments = - build_arguments(payload, edge_vec_float, channels, widths); - arguments.system_node_count = node_count; - arguments.descriptor = descriptor.data_ptr(); - arguments.state_out = state.data_ptr(); - arguments.type_mismatch = &evaluation_words->node_types.type_mismatch; - arguments.largest_radius = &evaluation_words->node_types.largest_radius; - arguments.type_present = - present_types(arguments, &evaluation_words->node_types); - dispatch(channels, false, arguments, stream); + f_outer}; + + // === Steps 2 to 4. Charges, long range and cotangent of the descriptor === + // Over the owned nodes, whose descriptor rows the first step has filled. + deepmd::long_range::ChargeSumOutputs long_range; + const auto form_cotangent = [&] { + // === Step 2. Charges of the nodes and their descriptor Jacobian === + // The charge of a node is a function of the descriptor of that node + // alone, so the cotangent of its descriptor through the charge network + // is the derivative of the energy with respect to the charge times the + // Jacobian row of the charge, the input cotangent of a unit seed. A run + // of the fused network forms the charges and those rows in one pass, + // before the long range forms the derivative and the energy fitting + // overwrites the descriptor; a run of the per-layer kernels forms its + // charges here and its rows from their saved pre-activations after the + // energy fitting. + const auto charge_bias_double = + charge_bias.to(torch::kFloat64).contiguous(); + const FittingNetwork charge_fitting{ + charge_plan, charge_ws, charge_bs, charge_resnets, + charge_w_head, charge_b_head, charge_bias_double, charge_act}; + const FittingRuns charge_runs(stream, charge_fitting, run, owned, + std::move(charge_fitting_routes), f32, true); + const auto unit_seed = torch::ones({run}, f64); + // The long range reads the charge of every node, a halo row included. + auto raw_charge = node_buffer(block_count, {node_count}, f64); + auto charge_jacobian = torch::empty({node_count, width}, f32); + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + charge_runs.forward( + stream, begin, count, descriptor.data_ptr() + begin * width, + charge_jacobian.data_ptr() + begin * width, width, + node_type.data_ptr() + begin, unit_seed.data_ptr(), + raw_charge.data_ptr() + begin); + } - // === Step 2. Charges of the nodes and their descriptor Jacobian === - // The charge of a node is a function of the descriptor of that node alone, - // so the cotangent of its descriptor through the charge network is the - // derivative of the energy with respect to the charge times the Jacobian - // row of the charge, the input cotangent of a unit seed. A run of the fused - // network forms the charges and those rows in one pass, before the long - // range forms the derivative and the energy fitting overwrites the - // descriptor; a run of the per-layer kernels forms its charges here and - // its rows from their saved pre-activations after the energy fitting. - const long run = tile > 0 - ? std::max(1, std::min(tile, node_count)) - : node_count; - const long width = widths.output_width; - const auto charge_bias_double = charge_bias.to(torch::kFloat64).contiguous(); - const FittingNetwork charge_fitting{ - charge_plan, charge_ws, charge_bs, charge_resnets, - charge_w_head, charge_b_head, charge_bias_double, charge_act}; - const FittingRuns charge_runs(stream, charge_fitting, run, node_count, - std::move(charge_fitting_routes), f32, true); - const auto unit_seed = torch::ones({run}, f64); - auto raw_charge = torch::empty({node_count}, f64); - auto charge_jacobian = torch::empty({node_count, width}, f32); - for (long begin = 0; begin < node_count; begin += run) { - const long count = std::min(run, node_count - begin); - charge_runs.forward( - stream, begin, count, descriptor.data_ptr() + begin * width, - charge_jacobian.data_ptr() + begin * width, width, - node_type.data_ptr() + begin, unit_seed.data_ptr(), - raw_charge.data_ptr() + begin); - } - - // === Step 3. Long range of the charges === - // The per-node virials of the charged nodes sum to the virial of each frame, - // which the frame totals form with those of the descriptor. - const auto long_range = deepmd::long_range::latent_charge_sum( - coord, raw_charge.to(torch::kFloat32).unsqueeze(1), charged, n_node, - total_charge, box, coefficient, communicator, kernel, channel, prefactor, - order, spacing); - const torch::Tensor& long_range_energy = std::get<0>(long_range); - const torch::Tensor& charge_gradient = std::get<1>(long_range); - const torch::Tensor& long_range_force = std::get<2>(long_range); - const torch::Tensor& long_range_atom_virial = std::get<3>(long_range); - - // === Step 4. Cotangent of the descriptor === - // The cotangent of the energy fitting replaces the descriptor run by run; - // the runs of the per-layer kernels of the charge network then form their - // Jacobian rows, and the rows, scaled by the derivative of the energy with - // respect to the charges, add the cotangent of the charge network. - const FittingNetwork fitting{plan, ws, bs, resnets, - w_head, b_head, bias_atom_e, act}; - const FittingRuns runs(stream, fitting, run, node_count, - std::move(fitting_routes), f32); - for (long begin = 0; begin < node_count; begin += run) { - const long count = std::min(run, node_count - begin); - float* const run_descriptor = descriptor.data_ptr() + begin * width; - runs.output_and_cotangent( - stream, begin, count, run_descriptor, run_descriptor, width, - node_type.data_ptr() + begin, seed.data_ptr() + begin, - raw_energy.data_ptr() + begin); - } - for (long begin = 0; begin < node_count; begin += run) { - const long count = std::min(run, node_count - begin); - charge_runs.backward(stream, begin, count, unit_seed.data_ptr(), - charge_jacobian.data_ptr() + begin * width); - } - descriptor.addcmul_(charge_jacobian, charge_gradient); - - // === Step 5. Descriptor backward and force assembly === - arguments.descriptor_gradient = descriptor.data_ptr(); - arguments.state = state.data_ptr(); - arguments.moment_gradient = state.data_ptr(); - arguments.force = - reinterpret_cast(force_fixed.data_ptr()); - arguments.node_virial = node_virial.data_ptr(); - arguments.edge_gradient = - atom_virial ? edge_gradient.data_ptr() : nullptr; - arguments.clear_padding = true; - dispatch(channels, true, arguments, stream); + // === Step 3. Long range of the charges === + // The per-node virials of the charged nodes sum to the virial of each + // frame, which the frame totals form with those of the descriptor. + const auto sum_long_range = [&] { + long_range = deepmd::long_range::latent_charge_sum( + coord, raw_charge.to(torch::kFloat32).unsqueeze(1), charged, n_node, + total_charge, box, coefficient, communicator, kernel, channel, + prefactor, order, spacing); + }; + // Across ranks the sum waits on the host for the device before each of + // its exchanges, and the device idles while the host exchanges and + // launches what follows. The energy fitting and the Jacobian rows read no + // part of the sum, so there they are enqueued first and the sum runs on + // the side stream, whose waits cover the charges alone; the device then + // evaluates the fitting while the host exchanges. The fitting occupies + // every multiprocessor, and the high priority of the side stream lets the + // kernels that prepare an exchange take the first multiprocessors that a + // wave of the fitting frees. + const bool across_ranks = + deepmd::long_range::domain_count(communicator) > 1; + if (!across_ranks) { + sum_long_range(); + } + + // === Step 4. Cotangent of the descriptor === + // The cotangent of the energy fitting replaces the descriptor run by run; + // the runs of the per-layer kernels of the charge network then form their + // Jacobian rows, and the rows, scaled by the derivative of the energy + // with respect to the charges, add the cotangent of the charge network. + at::cuda::CUDAEvent charges_ready; + if (across_ranks) { + charges_ready.record(stream); + } + const FittingNetwork fitting{plan, ws, bs, resnets, + w_head, b_head, bias_atom_e, act}; + const FittingRuns runs(stream, fitting, run, owned, + std::move(fitting_routes), f32); + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + float* const run_descriptor = + descriptor.data_ptr() + begin * width; + runs.output_and_cotangent( + stream, begin, count, run_descriptor, run_descriptor, width, + node_type.data_ptr() + begin, seed.data_ptr() + begin, + raw_energy.data_ptr() + begin); + } + for (long begin = 0; begin < owned; begin += run) { + const long count = std::min(run, owned - begin); + charge_runs.backward(stream, begin, count, unit_seed.data_ptr(), + charge_jacobian.data_ptr() + begin * width); + } + if (across_ranks) { + const c10::cuda::CUDAStream side = side_stream(descriptor.get_device()); + charges_ready.block(side); + { + const c10::cuda::CUDAStreamGuard guard(side); + sum_long_range(); + } + // The outputs of the sum are read on the current stream, so their + // memory is reused only after that stream has read them. + for (const torch::Tensor& output : + {std::get<0>(long_range), std::get<1>(long_range), + std::get<2>(long_range), std::get<3>(long_range), + std::get<4>(long_range)}) { + output.record_stream(stream); + } + at::cuda::CUDAEvent summed; + summed.record(side); + summed.block(stream); + } + const torch::Tensor& charge_gradient = std::get<1>(long_range); + descriptor.narrow(0, 0, owned) + .addcmul_(charge_jacobian.narrow(0, 0, owned), + charge_gradient.narrow(0, 0, owned)); + }; + + torch::Tensor block_virial; + if (block_count > 0) { + // === Steps 1 and 5 over the blocks === + // The launch of the first block over a run fills the descriptor rows of + // the run, which the head reads with those of every other owned node. + const auto first_arguments = [&](long begin, long count) { + return first_block_run(payload, edge_vec_float, channels, widths, owned, + begin, count, + descriptor.data_ptr() + begin * width, + state.data_ptr(), evaluation_words); + }; + // The force assembly of the edge backward of the first block over a run. + // Only the final run reaches the reserved edge slots; its row pointer ends + // at the last physical edge, which is exactly where the padding begins. + const auto attach_force = [&](Arguments& arguments, long begin, + long count) { + arguments.force = reinterpret_cast( + force_fixed.data_ptr()); + arguments.node_virial = node_virial.data_ptr() + begin * 9; + arguments.edge_gradient = + atom_virial ? edge_gradient.data_ptr() : nullptr; + arguments.clear_padding = begin + count == owned; + }; + const EdgeGraph graph{destination_row_ptr, source, edge_vec_float}; + const BlockHead head{nullptr, form_cotangent}; + const torch::Tensor no_spin_gradient; + const BlockPass pass{ + kOp, + further.records, + rcut, + further.cutoffs, + graph, + halo, + channels, + static_cast(lmax), + /*has_spin=*/false, + f_outer > f_inner, + widths, + node_count, + run, + head, + descriptor, + state, + no_spin_gradient, + reinterpret_cast(force_fixed.data_ptr()), + stream}; + block_virial = evaluate_further_blocks(pass, first_arguments, attach_force); + } else { + // === Step 1. Descriptor and moment state of every node === + Arguments arguments = + first_block_run(payload, edge_vec_float, channels, widths, node_count, + 0, node_count, descriptor.data_ptr(), + state.data_ptr(), evaluation_words); + dispatch(channels, false, arguments, stream); + + form_cotangent(); + + // === Step 5. Descriptor backward and force assembly === + arguments.descriptor_gradient = descriptor.data_ptr(); + arguments.state = state.data_ptr(); + arguments.moment_gradient = state.data_ptr(); + arguments.force = + reinterpret_cast(force_fixed.data_ptr()); + arguments.node_virial = node_virial.data_ptr(); + arguments.edge_gradient = + atom_virial ? edge_gradient.data_ptr() : nullptr; + arguments.clear_padding = true; + dispatch(channels, true, arguments, stream); + } // === Step 6. Node results and frame totals === + // The further blocks attribute the virial of every edge to the node that + // emits it, its source, which is how the per-atom virial attributes it, so + // the frame virial and the per-atom virial take it as it is. + if (block_virial.defined()) { + node_virial.add_(block_virial); + } const EpilogueInputs step{n_node, frame_row_ptr, force_fixed, raw_energy, seed, node_virial, evaluation_words}; const SourceVirialTerms source_terms{edge_gradient, edge_vec_float, source_row_ptr, source_order}; - const LongRangeTerms long_range_terms{long_range_energy, long_range_force, - long_range_atom_virial}; - finish_energy_force(stream, node_count, blocks, step, nullptr, + const LongRangeTerms long_range_terms{std::get<0>(long_range), + std::get<2>(long_range), + std::get<3>(long_range)}; + finish_energy_force(stream, node_count, epilogue, step, nullptr, atom_virial ? &source_terms : nullptr, &long_range_terms, energy, atom_energy, force, virial, atom_virial_output); + if (block_virial.defined() && atom_virial) { + atom_virial_output.add_(block_virial.reshape({node_count, 3, 3})); + } return {energy, atom_energy, force, virial, atom_virial_output, mask}; } diff --git a/source/op/pt/dpa4c/graph_compress.cuh b/source/op/pt/dpa4c/graph_compress.cuh index d7a8d47055..29ebe3795d 100644 --- a/source/op/pt/dpa4c/graph_compress.cuh +++ b/source/op/pt/dpa4c/graph_compress.cuh @@ -164,11 +164,23 @@ __device__ __forceinline__ TableRow table_row(const float* table, reinterpret_cast(row + 4 * width)}; } -__device__ __forceinline__ float evaluate_table(const TableRow& row, - int channel, - float x) { - const float4 low = __ldg(row.quartet + channel); - const float2 high = __ldg(row.pair + channel); +/// The six spline coefficients of one channel of an interval row. A caller +/// that evaluates several channels loads all of their coefficients before it +/// evaluates the first, so that the loads overlap. +struct TableCoefficients { + float4 low; + float2 high; +}; + +__device__ __forceinline__ TableCoefficients +table_coefficients(const TableRow& row, int channel) { + return {__ldg(row.quartet + channel), __ldg(row.pair + channel)}; +} + +__device__ __forceinline__ float spline_value(const TableCoefficients& k, + float x) { + const float4 low = k.low; + const float2 high = k.high; return low.x + (low.y + (low.z + (low.w + (high.x + high.y * x) * x) * x) * x) * x; } @@ -179,10 +191,10 @@ __device__ __forceinline__ float evaluate_table(const TableRow& row, /// fewer instructions but serializes them into one chain of ten dependent /// products; the two shorter chains below overlap and measure faster at the /// widest channel profile. -__device__ __forceinline__ float2 evaluate_table_with_derivative( - const TableRow& row, int channel, float x, bool clamped) { - const float4 low = __ldg(row.quartet + channel); - const float2 high = __ldg(row.pair + channel); +__device__ __forceinline__ float2 spline_value_with_derivative( + const TableCoefficients& k, float x, bool clamped) { + const float4 low = k.low; + const float2 high = k.high; const float value = low.x + (low.y + (low.z + (low.w + (high.x + high.y * x) * x) * x) * x) * x; @@ -193,6 +205,18 @@ __device__ __forceinline__ float2 evaluate_table_with_derivative( return make_float2(value, clamped ? 0.0f : derivative); } +__device__ __forceinline__ float evaluate_table(const TableRow& row, + int channel, + float x) { + return spline_value(table_coefficients(row, channel), x); +} + +__device__ __forceinline__ float2 evaluate_table_with_derivative( + const TableRow& row, int channel, float x, bool clamped) { + return spline_value_with_derivative(table_coefficients(row, channel), x, + clamped); +} + /// Accumulate the pair-conditioned radial mode residual of one channel. /// /// The mode axis is innermost in the ordered mixing cache, so a supported rank @@ -389,11 +413,33 @@ struct EdgeGeometry { // window, the true one everywhere else. float seen; float envelope; + // Leave-one-out source gate, which the envelope carries; one without a + // source gate (Arguments::source_gate). + float gate; int source_type; // Retained for the native spin branch, which gathers the source moment. long source; }; +/// The leave-one-out source gate of an edge whose own bridging switch is +/// ``weight``, from the totals of the switches of the pairs of its source +/// (Arguments::source_gate): the product of the switches of every other pair +/// of the source, zero when one of them is zero. +__device__ __forceinline__ float leave_one_out_gate(float2 totals, + float weight) { + const bool frozen = weight <= 0.0f; + if (totals.y - (frozen ? 1.0f : 0.0f) > 0.5f) { + return 0.0f; + } + return __expf(totals.x - (frozen ? 0.0f : __logf(weight))); +} + +/// Whether a node has a pair inside its bridging window, whose switch its +/// totals (Arguments::source_gate) then record. +__device__ __forceinline__ bool has_window_pair(float2 totals) { + return totals.x != 0.0f || totals.y != 0.0f; +} + /// Length from which no bond of the row of a centre with radius /// `center_radius` lies inside its bridging window, or positive infinity when /// the launch carries no largest radius (see `Arguments::largest_radius`). The @@ -428,7 +474,8 @@ load_geometry(long edge, float bound, const float* contact_radius, float eps, - const float* edge_vec) { + const float* edge_vec, + const float2* source_gate) { EdgeGeometry geometry; geometry.source = source; geometry.source_type = source_type; @@ -443,7 +490,9 @@ load_geometry(long edge, geometry.uz = z * geometry.inverse_radius; geometry.seen = geometry.radius; geometry.envelope = c3_envelope(geometry.radius, rcut); + geometry.gate = 1.0f; if constexpr (Bridged) { + float weight = 1.0f; if (geometry.radius < bound) { const float contact = center_radius + __ldg(contact_radius + geometry.source_type); @@ -451,10 +500,17 @@ load_geometry(long edge, const float t = window_parameter(__fdividef(geometry.radius, contact), f_inner, inverse_f_width); geometry.seen = clamped_length(t, contact, f_inner, f_outer); - geometry.envelope = - c3_envelope(geometry.seen, rcut) * bridging_switch(t); + weight = bridging_switch(t); + geometry.envelope = c3_envelope(geometry.seen, rcut) * weight; } } + // The gate of an edge reads the pairs of its source rather than its own + // length, so it applies to every edge, whatever the window bound of its + // row. + if (source_gate != nullptr) { + geometry.gate = leave_one_out_gate(source_gate[source], weight); + geometry.envelope *= geometry.gate; + } } return geometry; } @@ -489,18 +545,30 @@ __device__ __forceinline__ float radial_chain(const EdgeGeometry& geometry, const float seen = clamped_length(t, contact, args.f_inner, args.f_outer); const float weight = bridging_switch(t); - const float slope = fmaf( - c3_envelope_derivative(seen, args.rcut) * weight, weight, - c3_envelope(seen, args.rcut) * - __fdividef(bridging_switch_derivative(t, args.inverse_f_width), - contact)); - return fmaf(envelope_gradient, slope, table_gradient * weight); + // Under a source gate the envelope is c3(r̃) w times the product of + // the switches of the other pairs of the source, that is c3(r̃) times + // the product over all of them. The slope of the switch then enters + // through the gate of every edge of the source, which + // gate_closure_kernel adds, and the edge keeps c3'(r̃) w^2. + const float switch_slope = + args.source_gate != nullptr + ? 0.0f + : c3_envelope(seen, args.rcut) * + __fdividef( + bridging_switch_derivative(t, args.inverse_f_width), + contact); + const float slope = + fmaf(c3_envelope_derivative(seen, args.rcut) * weight, weight, + switch_slope); + return fmaf(envelope_gradient, slope * geometry.gate, + table_gradient * weight); } } } - return fmaf(envelope_gradient, - c3_envelope_derivative(geometry.radius, args.rcut), - table_gradient); + return fmaf( + envelope_gradient, + c3_envelope_derivative(geometry.radius, args.rcut) * geometry.gate, + table_gradient); } // The Cartesian harmonics are evaluated on the unit direction, so the squared diff --git a/source/op/pt/dpa4c/graph_compress_kernel.cuh b/source/op/pt/dpa4c/graph_compress_kernel.cuh index ab7960b8b1..59b9c11aee 100644 --- a/source/op/pt/dpa4c/graph_compress_kernel.cuh +++ b/source/op/pt/dpa4c/graph_compress_kernel.cuh @@ -17,6 +17,7 @@ #include #include +#include "block_launch.h" #include "graph_compress.cuh" namespace deepmd_dpa4c { @@ -1151,7 +1152,7 @@ __global__ __launch_bounds__( const EdgeGeometry geometry = load_geometry( edge, source, source_type, args.rcut, args.f_inner, args.f_outer, args.inverse_f_width, center_radius, bound, args.contact_radius, - args.eps, args.edge_vec); + args.eps, args.edge_vec, args.source_gate); const TableLocation location = locate_table( geometry.seen, args.table_stride, args.table_max, args.interval_count); const TableRow row = @@ -1914,11 +1915,13 @@ __global__ __launch_bounds__( // The invariant readout of the nodes whose moments the edge scan published: // the degree alignment, the probe projections and every invariant block of -// the descriptor except the two divisors, which the scan emits itself. One -// warp owns one node, as in the scan. The readout is a launch of its own -// because the radial table rows that bound the scan are served by L1, whose -// capacity follows the carveout the scan's shared memory selects; the readout -// buffers of a resident node would double that carveout at full occupancy. +// the descriptor except the two divisors, which the scan emits itself, or +// which the readout copies from ``divisors`` when it is launched apart from +// the scan. One warp owns one node, as in the scan. The readout is a launch of +// its own because the radial table rows that bound the scan are served by L1, +// whose capacity follows the carveout the scan's shared memory selects; the +// readout buffers of a resident node would double that carveout at full +// occupancy. template __global__ __launch_bounds__(kWarpSize) void forward_readout_kernel( Arguments args) { @@ -1994,6 +1997,10 @@ __global__ __launch_bounds__(kWarpSize) void forward_readout_kernel( __syncthreads(); // === Step 2. Emit the invariant blocks === + if (args.divisors != nullptr && thread < 2) { + args.descriptor[node * P::OutputWidth + P::OutputDivisor + thread] = + args.divisors[node * 2 + thread]; + } for (int channel = thread; channel < Channels; channel += P::Threads) { store_descriptor(args.descriptor, args.output_mean, args.output_inv_std, node, P::OutputWidth, P::OutputScalar + channel, @@ -3451,7 +3458,7 @@ __global__ __launch_bounds__( const EdgeGeometry geometry = load_geometry( edge, source, source_type, args.rcut, args.f_inner, args.f_outer, args.inverse_f_width, center_radius, bound, args.contact_radius, - args.eps, args.edge_vec); + args.eps, args.edge_vec, args.source_gate); const TableLocation location = locate_table( geometry.seen, args.table_stride, args.table_max, args.interval_count); // The pair term depends on the geometry alone, so it starts here and runs @@ -3983,6 +3990,21 @@ __global__ __launch_bounds__( radial_gradient, envelope_gradient); if constexpr (Bridged) { radial_gradient = fmaf(pair_weight, pair_slope, radial_gradient); + // Under a source gate the envelope of an edge enters the gate of every + // other edge of its source, so its cotangent times the envelope joins + // the totals of a source with a pair inside its window, from which + // gate_closure_kernel forms the slope of the switches of that source. + if (args.gate_sums != nullptr) { + const float sum = subwarp_allsum(envelope_gradient, mask) * + geometry.envelope; + if (thread == leader && + has_window_pair(args.source_gate[geometry.source])) { + if (args.force != nullptr) { + check_force_range(sum, args.force + geometry.source * kForceWords); + } + atomicAdd(args.gate_sums + geometry.source, fixed_point(sum)); + } + } } // The basis VJP is linear in the radial and angular cotangents, so @@ -4438,12 +4460,22 @@ struct BackwardLauncher { <<>>(args); } - static void run(const Arguments& args, cudaStream_t stream) { + /// The readout VJP of every node of the launch into its moment gradient. + static void run_nodes(const Arguments& args, cudaStream_t stream) { if (prefer_wide_nodes()) { launch_node_backward(args, stream); } else { launch_node_backward(args, stream); } + } + + static void run(const Arguments& args, cudaStream_t stream) { + run_nodes(args, stream); + run_edges(args, stream); + } + + /// The edge recomputation scans from the moment gradient of every node. + static void run_edges(const Arguments& args, cudaStream_t stream) { launch_edge_scans(args, stream); // The reserved edge slots beyond the physical count are only known on the @@ -4554,4 +4586,69 @@ void launch_backward(const Arguments& arguments, cudaStream_t stream) { dispatch_modes(arguments, stream); } +// The stages of the first block that a descriptor of several blocks launches +// one at a time (FirstStage). +template +struct ReadoutLauncher { + static void run(const Arguments& args, cudaStream_t stream) { + using P = Profile; + forward_readout_kernel + <<(args.node_count), P::Threads, 0, stream>>>(args); + } +}; + +template +struct NodeBackwardLauncher { + static void run(const Arguments& args, cudaStream_t stream) { + BackwardLauncher::run_nodes(args, stream); + } +}; + +template +struct EdgeBackwardLauncher { + static void run(const Arguments& args, cudaStream_t stream) { + BackwardLauncher::run_edges(args, stream); + } +}; + +template +void launch_first_stage(FirstStage stage, + const Arguments& arguments, + cudaStream_t stream) { + if (arguments.node_count == 0) { + return; + } + switch (stage) { + case FirstStage::Readout: + dispatch_modes(arguments, stream); + return; + case FirstStage::NodeBackward: + dispatch_modes(arguments, stream); + return; + case FirstStage::EdgeBackward: + dispatch_modes(arguments, stream); + return; + } +} + } // namespace deepmd_dpa4c diff --git a/source/op/pt/dpa4c/graph_compress_launch.h b/source/op/pt/dpa4c/graph_compress_launch.h index d67ce0d1b3..66c2da53c3 100644 --- a/source/op/pt/dpa4c/graph_compress_launch.h +++ b/source/op/pt/dpa4c/graph_compress_launch.h @@ -41,11 +41,13 @@ constexpr int kFoldedModes = 4; /// 64-bit fixed point, and the pair energy fp64. struct Arguments { long node_count = 0; - // Node count of the whole system, from which the edge scans choose their - // row split and their co-scheduled blocks, both of which change the - // summation order of a row, so that every run of a tiled system takes the - // schedule of the whole system. + // Rows of the whole system that the operator evaluates -- every node, or the + // owned nodes of a node set with halo rows -- from which the edge scans + // choose their row split and their co-scheduled blocks, both of which change + // the summation order of a row, so that every run of a tiled system takes + // the schedule of the whole system. long system_node_count = 0; + // Slots of the edge storage, at least the edges of every row. long edge_count = 0; int lmax = 2; int interval_count = 0; @@ -136,6 +138,21 @@ struct Arguments { // and this radius long, so the edge scans resolve the window of a pair only // for the shorter bonds of the row. const float* largest_radius = nullptr; + // === Source gate of a bridged descriptor of several blocks === + // A descriptor of several blocks with a bridging window mutes every edge + // that an atom inside the frozen zone of a pair emits towards a third atom: + // the envelope of an edge carries the product of the switches of every + // other pair of its source, its leave-one-out gate. ``source_gate`` holds, + // per node over the absolute node axis, the two totals of the switches of + // the pairs of the node, the sum of the logarithms of the nonzero ones and + // the number of zero ones (source_gate_kernel). ``gate_sums`` holds, per + // node over the absolute node axis, signed fixed-point sums in units of + // ``1 / kForceFixedScale``, onto which the edge backward adds the envelope + // cotangent times the envelope of every edge whose source has a pair inside + // its window (see gate_closure_kernel). Both are null for a descriptor of + // one block or without a window, and ``gate_sums`` for a forward launch. + const float2* source_gate = nullptr; + unsigned long long* gate_sums = nullptr; // === Native spin === // Present together or not at all. ``spin`` is indexed by absolute node id, @@ -163,6 +180,10 @@ struct Arguments { float* descriptor = nullptr; float* state_out = nullptr; float* moment_gradient = nullptr; + // Divisor columns of the descriptor, two per node and offset by the caller + // like ``descriptor``, which a readout launched apart from the scan that + // emits them copies (FirstStage::Readout); null for every other launch. + const float* divisors = nullptr; // Per-edge energy cotangent. A null pointer skips the store, which a // backward that assembles the force itself only needs for the per-atom // virial. diff --git a/source/op/pt/dpa4c/ops.cc b/source/op/pt/dpa4c/ops.cc index c249513fbe..ba8c0225a2 100644 --- a/source/op/pt/dpa4c/ops.cc +++ b/source/op/pt/dpa4c/ops.cc @@ -34,6 +34,19 @@ // CSR; a two-entry placeholder in place of `source_row_ptr` and // `source_order` declines it, which leaves it zero. // +// A descriptor of several message-passing blocks passes the records of its +// further blocks as `blocks`, one row per block in the layout of +// deepmd/pt_expt/kernels/dpa4c/attention.py, and may pass their cutoffs in Å +// as `block_rcut`, one per record, none above the one before or above `rcut`: +// a further block of a smaller cutoff than the block before then scans the +// edges inside it alone, and without them every further block scans the edges +// of the first. A descriptor of one block passes none or an empty matrix, and +// no cutoffs. A node set of a decomposed domain that holds halo +// rows after its owned rows passes their border plan, `halo_send`, +// `halo_swaps` and `communicator` (source/op/pt/border_exchange.h), with +// which the operator refreshes the features of the halo rows that the +// further blocks read; it then evaluates the owned rows alone. +// // The fused long-range operator evaluates a model whose atomic energy adds a // latent-charge long-range module with a charge network of one channel. It // takes the arguments of the fused operator up to `tile`, the network that @@ -41,9 +54,11 @@ // the layout of the energy fitting, with the per-type bias `charge_bias`), // the inputs of deepmd::latent_charge_sum (`coord` to `spacing`, see // source/op/pt/long_range/ops.cc), whose charged nodes are the owned real -// nodes, and the fitting routes. It returns the outputs of the fused operator -// but the magnetic force: the descriptor carries no spin condition and the -// model no pair potential. +// nodes, the fitting routes, and the further blocks with their cutoffs and +// the border plan of a node set with halo rows, as the fused operator takes +// them, whose halo exchange travels on `communicator`. It returns the outputs +// of the fused operator but the magnetic force: the descriptor carries no +// spin condition and the model no pair potential. // // Every schema carries, next to the radial table, the low-rank table and the // expansion that a single-type scan reads instead of the scalar-only channels @@ -134,7 +149,9 @@ TORCH_LIBRARY_FRAGMENT(deepmd, library) { "float degree_floor, float f_inner, float f_outer, " "Tensor[] ws, Tensor[] bs, int[] resnets, " "Tensor w_head, Tensor b_head, Tensor bias_atom_e, int act, " - "int tile, Tensor pair_table, int[]? fitting_routes=None) " + "int tile, Tensor pair_table, int[]? fitting_routes=None, " + "Tensor? blocks=None, Tensor? halo_send=None, Tensor? halo_swaps=None, " + "Tensor? communicator=None, float[]? block_rcut=None) " "-> (Tensor energy, Tensor atom_energy, Tensor force, Tensor virial, " "Tensor atom_virial, Tensor force_mag, Tensor mask)"); library.def( @@ -155,7 +172,9 @@ TORCH_LIBRARY_FRAGMENT(deepmd, library) { "int charge_act, Tensor coord, Tensor total_charge, Tensor? box, " "Tensor coefficient, Tensor communicator, int kernel, int channel, " "float prefactor, int order, float spacing, " - "int[]? fitting_routes=None, int[]? charge_fitting_routes=None) " + "int[]? fitting_routes=None, int[]? charge_fitting_routes=None, " + "Tensor? blocks=None, Tensor? halo_send=None, Tensor? halo_swaps=None, " + "float[]? block_rcut=None) " "-> (Tensor energy, Tensor atom_energy, Tensor force, Tensor virial, " "Tensor atom_virial, Tensor mask)"); } diff --git a/source/op/pt/dpa4c/shard.cu.in b/source/op/pt/dpa4c/shard.cu.in index db5fe904ef..a24eb2ef84 100644 --- a/source/op/pt/dpa4c/shard.cu.in +++ b/source/op/pt/dpa4c/shard.cu.in @@ -1,7 +1,8 @@ // SPDX-License-Identifier: LGPL-3.0-or-later // // Generated instantiation shard of the compressed DPA4C descriptor. The -// maintained kernels live in graph_compress_kernel.cuh; CMake selects the +// maintained kernels live in graph_compress_kernel.cuh, those of the further +// message-passing blocks in block_kernel.cuh; CMake selects the header, the // scalar width and the angular degrees of each source so that nvcc compiles // the template grid in parallel (see the shard layout in CMakeLists.txt). diff --git a/source/op/pt/graph_fitting.cu b/source/op/pt/graph_fitting.cu index dec91756da..46091db593 100644 --- a/source/op/pt/graph_fitting.cu +++ b/source/op/pt/graph_fitting.cu @@ -77,9 +77,12 @@ #include "fp32_ridge.h" #include "graph_ops.h" +#include "simt_gemm.cuh" namespace { +using namespace deepmd_gemm; + #define FITTING_CHECK_LAUNCH(what) \ do { \ cudaError_t err = cudaGetLastError(); \ @@ -128,32 +131,12 @@ long ceil_div(long a, long b) { return (a + b - 1) / b; } // aligned float4 quads. // --------------------------------------------------------------------------- -__device__ __forceinline__ float4 zero4() { - return make_float4(0.f, 0.f, 0.f, 0.f); -} - -__device__ __forceinline__ float4 load4(const float* p) { - return __ldg(reinterpret_cast(p)); -} - /// Load through L2 only, for data that the kernel itself writes while it runs, /// which the read-only path of ``load4`` must not serve. __device__ __forceinline__ float4 load4_coherent(const float* p) { return __ldcg(reinterpret_cast(p)); } -__device__ __forceinline__ float4 lds4(const float* p) { - return *reinterpret_cast(p); -} - -__device__ __forceinline__ float2 lds2(const float* p) { - return *reinterpret_cast(p); -} - -__device__ __forceinline__ void store4(float* p, float4 v) { - *reinterpret_cast(p) = v; -} - __device__ __forceinline__ float4 add4(float4 a, float4 b) { return make_float4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } @@ -192,75 +175,6 @@ __device__ __forceinline__ float4 act_derivative4(float4 z) { act_derivative(z.z), act_derivative(z.w)); } -/// Request the line holding ``p`` into L2. -__device__ __forceinline__ void prefetch_l2(const float* p) { - asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); -} - -/// Depth slices by which the streamed node-major operands are requested into -/// L2 ahead of their register load. The register stage hides one slice of -/// latency; the prefetch covers the DRAM latency beyond it, which dominates -/// once the run outgrows L2. -constexpr int kLookahead = 2; - -// --------------------------------------------------------------------------- -// GEMM tiles. -// -// A CTA computes a ``rows`` x ``cols`` block of C = A @ B, A the node-major -// (nodes, K) operand and B the (K, cols) weight operand, in ``depth``-deep -// slices staged through double-buffered shared memory: the global loads of -// slice s + 1 are in flight in registers while slice s is multiplied. A warp -// is 4 x 8 lanes and a lane owns tm x tn accumulators as blocks of -// row_group x 4, at rows r + h * row_stride + [0, row_group) and columns -// c + g * col_stride + [0, 4) from its origin (r, c), where a row group is a -// quad, or a pair for a lane of two rows. The four lane rows of a warp read -// adjacent 16- or 8-byte words of a shared A row and its eight lane columns -// adjacent 16-byte words of a shared B row. The lane rows and columns are -// lane / 8 and lane % 8, or, for a tile with ``paired_columns``, lane / 2 % 4 -// and 2 * (lane / 8) + lane % 2, which gives each quarter-warp two adjacent -// B words instead of all eight. On sm_120 a 16-byte B read then takes two -// shared wavefronts instead of four, while the A reads keep theirs: one per -// 8-byte and two per 16-byte read in either layout. -// --------------------------------------------------------------------------- - -/// Shared rows carry four floats of skew. Every tile extent is a multiple of -/// 32 floats, so the row stride is congruent to 4 modulo the 32 banks, which -/// spreads the transposing scalar stores of a warp over 32 banks while every -/// row stays 16-byte aligned. -constexpr int kSkew = 4; - -template -struct GemmTile { - static constexpr int rows = kRows; - static constexpr int cols = kCols; - static constexpr int tm = kThreadRows; - static constexpr int tn = kThreadCols; - static constexpr int depth = kDepth; - static constexpr int warp_cols = kWarpCols; - static constexpr int threads = 32 * kWarpRows * kWarpCols; - static constexpr int min_blocks = kMinBlocks; - static constexpr int row_group = 4; - static constexpr bool paired_columns = false; - static constexpr int row_stride = kRows / (kThreadRows / 4); - static constexpr int col_stride = kCols / (kThreadCols / 4); - static_assert(kThreadRows % 4 == 0 && kThreadCols % 4 == 0, - "a lane owns whole row and column quads"); - static_assert(kRows == 4 * kThreadRows * kWarpRows && - kCols == 8 * kThreadCols * kWarpCols, - "a warp covers 4 tm rows and 8 tn columns as 4 x 8 lanes"); - static_assert(kRows % 32 == 0 && kCols % 32 == 0 && kDepth % 8 == 0, - "tile extents are whole 32-row, 32-column, 8-deep blocks"); - static_assert(kCols / (kThreadCols / 4) % 32 == 0, - "the eight lane columns of a quad cover one 32-column group"); -}; - /// Large tile, 8 x 8 accumulators per lane, for grids of several waves. using LargeTile = GemmTile<64, 128, 8, 8, 8, 2, 2, 3>; /// Small tile with a four times finer grid for runs that would leave the @@ -268,283 +182,6 @@ using LargeTile = GemmTile<64, 128, 8, 8, 8, 2, 2, 3>; /// three CTAs resident per SM on sm_120. using SmallTile = GemmTile<32, 64, 4, 4, 32, 2, 2, 3>; -template -struct GemmStorage { - float a[2][Tile::depth][Tile::rows + kSkew]; - float b[2][Tile::depth][Tile::cols + kSkew]; -}; - -template -using Accumulators = float[Tile::tm][Tile::tn]; - -/// Tile-local row and column of a lane's first accumulator. -struct LaneOrigin { - int row; - int col; -}; - -/// Lane row and lane column of ``lane`` within the 4 x 8 lanes of its warp. -template -__device__ __forceinline__ int lane_row(int lane) { - return Tile::paired_columns ? lane / 2 % 4 : lane / 8; -} - -template -__device__ __forceinline__ int lane_col(int lane) { - return Tile::paired_columns ? 2 * (lane / 8) + lane % 2 : lane % 8; -} - -/// Lane distance between lane columns ``d`` apart, for d of 1, 2 or 4 within -/// one aligned group of eight, which a butterfly over the columns uses. -template -__device__ __forceinline__ constexpr int lane_col_stride(int d) { - return Tile::paired_columns && d > 1 ? 4 * d : d; -} - -template -__device__ __forceinline__ LaneOrigin lane_origin() { - const int warp = threadIdx.x / 32; - const int lane = threadIdx.x % 32; - return { - ((warp / Tile::warp_cols) * 4 + lane_row(lane)) * Tile::row_group, - ((warp % Tile::warp_cols) * 8 + lane_col(lane)) * 4}; -} - -/// Tile-local row of accumulator row ``i``. -template -__device__ __forceinline__ int accumulator_row(const LaneOrigin& o, int i) { - return o.row + (i / Tile::row_group) * Tile::row_stride + i % Tile::row_group; -} - -/// Tile-local column of the first accumulator of column quad ``g``. -template -__device__ __forceinline__ int accumulator_col(const LaneOrigin& o, int g) { - return o.col + g * Tile::col_stride; -} - -template -__device__ __forceinline__ float4 -accumulator_quad(const Accumulators& acc, int i, int g) { - return make_float4(acc[i][4 * g], acc[i][4 * g + 1], acc[i][4 * g + 2], - acc[i][4 * g + 3]); -} - -/// CTA tile of a one-dimensional grid: consecutive CTAs walk the column tiles -/// of one row tile, so they share their A rows while those are hot in L2. -struct TileIndex { - long row0; - int col0; -}; - -template -__device__ __forceinline__ TileIndex tile_index(int width) { - const int col_tiles = (width + Tile::cols - 1) / Tile::cols; - return {(long)(blockIdx.x / col_tiles) * Tile::rows, - (int)(blockIdx.x % col_tiles) * Tile::cols}; -} - -// --------------------------------------------------------------------------- -// Operand stagers. ``fetch(k0)`` issues the global loads of the slice -// [k0, k0 + Tile::depth) of the contraction axis, of length ``extent``, into -// registers and ``commit`` writes them to shared memory in the depth-major -// layout the fragments read. Depths past the extent are zero-filled; rows and -// columns past the matrix are clamped to its last row or column, whose finite -// values reach only accumulators that are never stored. -// --------------------------------------------------------------------------- - -/// Thread map of a ``kLines`` x depth slice read as float4 along depth and -/// stored depth-major. Lane pairs cover the 32-byte segment of one line in -/// each 8-deep group of the slice, so a warp reads 16 lines and its scalar -/// stores land on 32 distinct banks. -template -struct TransposedSlice { - static constexpr int count = kLines * Tile::depth / 4 / Tile::threads; - static_assert(count >= 1 && count * 4 * Tile::threads == kLines * Tile::depth, - "the threads must tile the slice evenly"); - static_assert(2 * kLines % 32 == 0, "a warp stays within one 8-deep group"); - __device__ static int line(int s) { - const int i = threadIdx.x + s * Tile::threads; - return (i / 2) % kLines; - } - __device__ static int quad(int s) { - const int i = threadIdx.x + s * Tile::threads; - return i % 2 + 2 * (i / (2 * kLines)); - } -}; - -template -__device__ __forceinline__ void store_transposed(float (*dst)[kLines + kSkew], - const float4 (&v)[kCount]) { - using Map = TransposedSlice; -#pragma unroll - for (int s = 0; s < kCount; ++s) { - const int q = 4 * Map::quad(s); - const int l = Map::line(s); - dst[q][l] = v[s].x; - dst[q + 1][l] = v[s].y; - dst[q + 2][l] = v[s].z; - dst[q + 3][l] = v[s].w; - } -} - -/// A operand read as stored from a row-major (nodes, K) tensor: the layer -/// input of the forward, or a dpre emitted for the backward. -template -struct InputStager; - -/// float4 loads, for 16-byte aligned rows. -template -struct InputStager { - using Map = TransposedSlice; - const float* src[Map::count]; - float4 v[Map::count]; - int extent; - - __device__ InputStager(const float* x, long row0, long nodes, int extent_) - : extent(extent_) { -#pragma unroll - for (int s = 0; s < Map::count; ++s) { - const long row = min(row0 + Map::line(s), nodes - 1); - src[s] = x + row * extent + 4 * Map::quad(s); - } - } - - __device__ __forceinline__ void fetch(int k0) { -#pragma unroll - for (int s = 0; s < Map::count; ++s) { - const int k = k0 + 4 * Map::quad(s); - v[s] = k < extent ? load4(src[s] + k0) : zero4(); - if (k + kLookahead * Tile::depth < extent) { - prefetch_l2(src[s] + k0 + kLookahead * Tile::depth); - } - } - } - - __device__ __forceinline__ void commit(float (*a)[Tile::rows + kSkew]) { - store_transposed(a, v); - } -}; - -/// Scalar loads, for any row stride: eight lanes cover the 32-byte segment of -/// one line and the warp's stores land on 32 distinct banks. -template -struct InputStager { - static constexpr int count = Tile::rows * Tile::depth / Tile::threads; - static_assert(count >= 1 && count * Tile::threads == Tile::rows * Tile::depth, - "the threads must tile the slice evenly"); - const float* src[count]; - float v[count]; - int extent; - - __device__ static int line(int s) { - const int i = threadIdx.x + s * Tile::threads; - return (i / 8) % Tile::rows; - } - __device__ static int col(int s) { - const int i = threadIdx.x + s * Tile::threads; - return i % 8 + 8 * (i / (8 * Tile::rows)); - } - - __device__ InputStager(const float* x, long row0, long nodes, int extent_) - : extent(extent_) { -#pragma unroll - for (int s = 0; s < count; ++s) { - const long row = min(row0 + line(s), nodes - 1); - src[s] = x + row * extent + col(s); - } - } - - __device__ __forceinline__ void fetch(int k0) { -#pragma unroll - for (int s = 0; s < count; ++s) { - const int k = k0 + col(s); - v[s] = k < extent ? __ldg(src[s] + k0) : 0.f; - if (k + kLookahead * Tile::depth < extent) { - prefetch_l2(src[s] + k0 + kLookahead * Tile::depth); - } - } - } - - __device__ __forceinline__ void commit(float (*a)[Tile::rows + kSkew]) { -#pragma unroll - for (int s = 0; s < count; ++s) { - a[col(s)][line(s)] = v[s]; - } - } -}; - -/// Forward B operand: the row-major (K, width) weight, read as float4 -/// along its output channels and stored as is. -template -struct WeightStager { - static constexpr int quads = Tile::cols / 4; - static constexpr int count = Tile::depth * quads / Tile::threads; - static_assert(count >= 1 && count * Tile::threads == Tile::depth * quads && - Tile::threads % quads == 0, - "the threads must tile the slice evenly"); - const float* src; - float4 v[count]; - int extent; - int width; - - __device__ static int line(int s) { - return (threadIdx.x + s * Tile::threads) / quads; - } - - __device__ WeightStager(const float* w, int col0, int extent_, int width_) - : src(w + min(col0 + 4 * (int)(threadIdx.x % quads), width_ - 4)), - extent(extent_), - width(width_) {} - - __device__ __forceinline__ void fetch(int k0) { -#pragma unroll - for (int s = 0; s < count; ++s) { - const int k = k0 + line(s); - v[s] = k < extent ? load4(src + (long)k * width) : zero4(); - } - } - - __device__ __forceinline__ void commit(float (*b)[Tile::cols + kSkew]) { -#pragma unroll - for (int s = 0; s < count; ++s) { - store4(&b[line(s)][4 * (threadIdx.x % quads)], v[s]); - } - } -}; - -/// Backward B operand: W^T for the row-major (width, K) weight W, read -/// as float4 along W's rows (the contraction axis) and stored transposed. -template -struct WeightTransposeStager { - using Map = TransposedSlice; - const float* src[Map::count]; - float4 v[Map::count]; - int extent; - - __device__ WeightTransposeStager(const float* w, - int col0, - int extent_, - int width) - : extent(extent_) { -#pragma unroll - for (int s = 0; s < Map::count; ++s) { - const int n = min(col0 + Map::line(s), width - 1); - src[s] = w + (long)n * extent + 4 * Map::quad(s); - } - } - - __device__ __forceinline__ void fetch(int k0) { -#pragma unroll - for (int s = 0; s < Map::count; ++s) { - v[s] = k0 + 4 * Map::quad(s) < extent ? load4(src[s] + k0) : zero4(); - } - } - - __device__ __forceinline__ void commit(float (*b)[Tile::cols + kSkew]) { - store_transposed(b, v); - } -}; - /// Where a backward layer takes its A operand dpre = dh * act'(pre + b) from. enum class Cotangent { kHead, //!< Seed layer: dh = d_e[n] * w_head, dpre formed while staging. @@ -624,90 +261,6 @@ struct CotangentStager { } }; -// --------------------------------------------------------------------------- -// Main loop. Every accumulator sums the contraction axis in ascending order -// with one fused multiply-add per term, independent of the tile shape. -// --------------------------------------------------------------------------- - -template -__device__ __forceinline__ void multiply_slice( - const float (*a)[Tile::rows + kSkew], - const float (*b)[Tile::cols + kSkew], - const LaneOrigin& o, - Accumulators& acc) { -#pragma unroll - for (int k = 0; k < Tile::depth; ++k) { - float av[Tile::tm]; - float bv[Tile::tn]; -#pragma unroll - for (int h = 0; h < Tile::tm / Tile::row_group; ++h) { - const float* row = &a[k][o.row + h * Tile::row_stride]; - if constexpr (Tile::row_group == 4) { - const float4 v = lds4(row); - av[4 * h] = v.x; - av[4 * h + 1] = v.y; - av[4 * h + 2] = v.z; - av[4 * h + 3] = v.w; - } else { - const float2 v = lds2(row); - av[2 * h] = v.x; - av[2 * h + 1] = v.y; - } - } -#pragma unroll - for (int g = 0; g < Tile::tn / 4; ++g) { - const float4 v = lds4(&b[k][o.col + g * Tile::col_stride]); - bv[4 * g] = v.x; - bv[4 * g + 1] = v.y; - bv[4 * g + 2] = v.z; - bv[4 * g + 3] = v.w; - } -#pragma unroll - for (int i = 0; i < Tile::tm; ++i) { -#pragma unroll - for (int j = 0; j < Tile::tn; ++j) { - acc[i][j] = fmaf(av[i], bv[j], acc[i][j]); - } - } - } -} - -template -__device__ __forceinline__ void zero_accumulators(Accumulators& acc) { -#pragma unroll - for (int i = 0; i < S::tm; ++i) { -#pragma unroll - for (int j = 0; j < S::tn; ++j) { - acc[i][j] = 0.f; - } - } -} - -template -__device__ __forceinline__ void gemm_mainloop(GemmStorage& smem, - StagerA& sa, - StagerB& sb, - int extent, - const LaneOrigin& o, - Accumulators& acc) { - zero_accumulators(acc); - const int slices = (extent + Tile::depth - 1) / Tile::depth; - sa.fetch(0); - sb.fetch(0); - sa.commit(smem.a[0]); - sb.commit(smem.b[0]); - __syncthreads(); - for (int s = 0; s < slices; ++s) { - const int buf = s & 1; - sa.fetch((s + 1) * Tile::depth); - sb.fetch((s + 1) * Tile::depth); - multiply_slice(smem.a[buf], smem.b[buf], o, acc); - sa.commit(smem.a[buf ^ 1]); - sb.commit(smem.b[buf ^ 1]); - __syncthreads(); - } -} - // --------------------------------------------------------------------------- // Forward layer: pre = x @ W, y = act(pre + b) (+ x). // diff --git a/source/op/pt/long_range/domain_exchange.cc b/source/op/pt/long_range/domain_exchange.cc index cbe4f07a23..34c212e93d 100644 --- a/source/op/pt/long_range/domain_exchange.cc +++ b/source/op/pt/long_range/domain_exchange.cc @@ -5,70 +5,42 @@ // // With an MPI library that reads device memory (MPIX_Query_cuda_support), the // rows travel between device buffers once the current stream has finished -// writing them; otherwise they are staged through pinned host buffers. Either -// way the host waits for the device once per exchange, before MPI reads the -// data; the results return to the device without a further wait. +// writing them, those of a gather as one point-to-point message between every +// pair of ranks, which the library transfers between the device buffers of +// the two ranks; otherwise they are staged through pinned host buffers, which +// a collective gathers. Either way the host waits for the device once per +// exchange, before MPI reads the data; the results return to the device +// without a further wait. #include "domain_exchange.h" -#ifdef USE_MPI -#include -#ifdef OMPI_MPI_H -#include -#endif -#endif #include #include #include #include +#include "../communicator.h" + namespace deepmd { namespace long_range { -namespace { -std::int64_t address_of(const torch::Tensor& communicator) { - TORCH_CHECK(communicator.device().is_cpu() && - communicator.scalar_type() == torch::kInt64 && - communicator.numel() == 1, - "latent_charge_sum: communicator must be an int64 CPU " - "tensor with one element"); - return communicator.contiguous().data_ptr()[0]; -} +/// The operator that names an exchange in its diagnostics. +constexpr const char* kOperator = "latent_charge_sum"; #ifdef USE_MPI -// The handle of the caller, of the width of MPI_Comm in this MPI library: an -// int in MPICH, a pointer in Open MPI. -MPI_Comm communicator_of(const torch::Tensor& communicator) { - static_assert(sizeof(std::uintptr_t) <= sizeof(std::int64_t), - "an address must fit in an int64 tensor"); - return *reinterpret_cast( - static_cast(address_of(communicator))); -} - -bool reads_device_memory() { -#ifdef NO_CUDA_AWARE - return false; -#else - return MPIX_Query_cuda_support() != 0; -#endif -} +/// Tag of the rows of a gather. Messages between two ranks are received in +/// the order they are sent, so one tag serves every gather. +constexpr int kGatherTag = 0x4c52; #endif -} // namespace - int domain_count(const torch::Tensor& communicator) { - if (address_of(communicator) == 0) { + if (communicator_address(communicator, kOperator) == 0) { return 1; } #ifdef USE_MPI - int initialized = 0; - MPI_Initialized(&initialized); - TORCH_CHECK(initialized != 0, - "latent_charge_sum: a communicator was given, but MPI is " - "not initialized"); int size = 1; - MPI_Comm_size(communicator_of(communicator), &size); + MPI_Comm_size(communicator_handle(communicator, kOperator), &size); return size; #else TORCH_CHECK(false, @@ -84,7 +56,7 @@ std::pair gather_domain_rows( rows.scalar_type() == torch::kFloat64 && rows.is_contiguous(), "gather_domain_rows: rows must be a contiguous float64 CUDA " "matrix"); - const MPI_Comm comm = communicator_of(communicator); + const MPI_Comm comm = communicator_handle(communicator, kOperator); int rank = 0; int size = 1; MPI_Comm_rank(comm, &rank); @@ -110,11 +82,30 @@ std::pair gather_domain_rows( } const int send_count = static_cast(local * width); auto gathered = torch::empty({total, width}, rows.options()); - if (reads_device_memory()) { + if (mpi_reads_device_memory()) { + // Every rank sends its rows to every other rank and receives theirs into + // their place; a rank of no rows sends nothing, which every rank knows + // from the counts. MPI reads the rows of the device once the stream has + // written them. + gathered.narrow(0, offset, local).copy_(rows); at::cuda::getCurrentCUDAStream().synchronize(); - MPI_Allgatherv(rows.data_ptr(), send_count, MPI_DOUBLE, - gathered.data_ptr(), receive_counts.data(), - displacements.data(), MPI_DOUBLE, comm); + std::vector requests; + requests.reserve(2 * static_cast(size)); + for (int r = 0; r < size; ++r) { + if (r != rank && receive_counts[r] > 0) { + MPI_Irecv(gathered.data_ptr() + displacements[r], + receive_counts[r], MPI_DOUBLE, r, kGatherTag, comm, + &requests.emplace_back()); + } + } + for (int r = 0; r < size && send_count > 0; ++r) { + if (r != rank) { + MPI_Isend(rows.data_ptr(), send_count, MPI_DOUBLE, r, + kGatherTag, comm, &requests.emplace_back()); + } + } + MPI_Waitall(static_cast(requests.size()), requests.data(), + MPI_STATUSES_IGNORE); } else { const auto host = rows.options().device(torch::kCPU).pinned_memory(true); auto host_rows = torch::empty({local, width}, host); @@ -138,7 +129,7 @@ torch::Tensor sum_over_domains(const torch::Tensor& communicator, #ifdef USE_MPI TORCH_CHECK(values.dim() == 1 && values.scalar_type() == torch::kFloat64, "sum_over_domains: values must be a float64 vector"); - const MPI_Comm comm = communicator_of(communicator); + const MPI_Comm comm = communicator_handle(communicator, kOperator); int size = 1; MPI_Comm_size(comm, &size); const torch::Tensor local = values.to(torch::kCPU).contiguous(); diff --git a/source/op/pt/simt_gemm.cuh b/source/op/pt/simt_gemm.cuh new file mode 100644 index 0000000000..b9eb0de4d5 --- /dev/null +++ b/source/op/pt/simt_gemm.cuh @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: LGPL-3.0-or-later +// +// FP32 SIMT GEMM tiles shared by the node-scale CUDA operators: the fitting +// network (graph_fitting.cu) and the node maps of the further DPA4C blocks +// (dpa4c/block_kernel.cuh). A CTA computes one tile of C = A @ B in +// double-buffered depth slices; the operand stagers read A and B from +// global memory, and a caller supplies stagers of its own that transform an +// operand while staging it. + +#pragma once + +#include + +namespace deepmd_gemm { + +// --------------------------------------------------------------------------- +// Vector helpers. An operand addressed in float4 quads is 16-byte aligned. +// --------------------------------------------------------------------------- + +__device__ __forceinline__ float4 zero4() { + return make_float4(0.f, 0.f, 0.f, 0.f); +} + +__device__ __forceinline__ float4 load4(const float* p) { + return __ldg(reinterpret_cast(p)); +} + +__device__ __forceinline__ float4 lds4(const float* p) { + return *reinterpret_cast(p); +} + +__device__ __forceinline__ float2 lds2(const float* p) { + return *reinterpret_cast(p); +} + +__device__ __forceinline__ void store4(float* p, float4 v) { + *reinterpret_cast(p) = v; +} + +/// Request the line holding ``p`` into L2. +__device__ __forceinline__ void prefetch_l2(const float* p) { + asm volatile("prefetch.global.L2 [%0];" ::"l"(p)); +} + +/// Depth slices by which the streamed node-major operands are requested into +/// L2 ahead of their register load. The register stage hides one slice of +/// latency; the prefetch covers the DRAM latency beyond it, which dominates +/// once the run outgrows L2. +constexpr int kLookahead = 2; + +// --------------------------------------------------------------------------- +// GEMM tiles. +// +// A CTA computes a ``rows`` x ``cols`` block of C = A @ B, A the node-major +// (nodes, K) operand and B the (K, cols) weight operand, in ``depth``-deep +// slices staged through double-buffered shared memory: the global loads of +// slice s + 1 are in flight in registers while slice s is multiplied. A warp +// is 4 x 8 lanes and a lane owns tm x tn accumulators as blocks of +// row_group x 4, at rows r + h * row_stride + [0, row_group) and columns +// c + g * col_stride + [0, 4) from its origin (r, c), where a row group is a +// quad, or a pair for a lane of two rows. The four lane rows of a warp read +// adjacent 16- or 8-byte words of a shared A row and its eight lane columns +// adjacent 16-byte words of a shared B row. The lane rows and columns are +// lane / 8 and lane % 8, or, for a tile with ``paired_columns``, lane / 2 % 4 +// and 2 * (lane / 8) + lane % 2, which gives each quarter-warp two adjacent +// B words instead of all eight. On sm_120 a 16-byte B read then takes two +// shared wavefronts instead of four, while the A reads keep theirs: one per +// 8-byte and two per 16-byte read in either layout. +// --------------------------------------------------------------------------- + +/// Shared rows carry four floats of skew. Every tile extent is a multiple of +/// 32 floats, so the row stride is congruent to 4 modulo the 32 banks, which +/// spreads the transposing scalar stores of a warp over 32 banks while every +/// row stays 16-byte aligned. +constexpr int kSkew = 4; + +template +struct GemmTile { + static constexpr int rows = kRows; + static constexpr int cols = kCols; + static constexpr int tm = kThreadRows; + static constexpr int tn = kThreadCols; + static constexpr int depth = kDepth; + static constexpr int warp_cols = kWarpCols; + static constexpr int threads = 32 * kWarpRows * kWarpCols; + static constexpr int min_blocks = kMinBlocks; + static constexpr int row_group = 4; + static constexpr bool paired_columns = false; + static constexpr int row_stride = kRows / (kThreadRows / 4); + static constexpr int col_stride = kCols / (kThreadCols / 4); + static_assert(kThreadRows % 4 == 0 && kThreadCols % 4 == 0, + "a lane owns whole row and column quads"); + static_assert(kRows == 4 * kThreadRows * kWarpRows && + kCols == 8 * kThreadCols * kWarpCols, + "a warp covers 4 tm rows and 8 tn columns as 4 x 8 lanes"); + static_assert(kRows % 32 == 0 && kCols % 32 == 0 && kDepth % 8 == 0, + "tile extents are whole 32-row, 32-column, 8-deep blocks"); + static_assert(kCols / (kThreadCols / 4) % 32 == 0, + "the eight lane columns of a quad cover one 32-column group"); +}; + +template +struct GemmStorage { + float a[2][Tile::depth][Tile::rows + kSkew]; + float b[2][Tile::depth][Tile::cols + kSkew]; +}; + +template +using Accumulators = float[Tile::tm][Tile::tn]; + +/// Tile-local row and column of a lane's first accumulator. +struct LaneOrigin { + int row; + int col; +}; + +/// Lane row and lane column of ``lane`` within the 4 x 8 lanes of its warp. +template +__device__ __forceinline__ int lane_row(int lane) { + return Tile::paired_columns ? lane / 2 % 4 : lane / 8; +} + +template +__device__ __forceinline__ int lane_col(int lane) { + return Tile::paired_columns ? 2 * (lane / 8) + lane % 2 : lane % 8; +} + +/// Lane distance between lane columns ``d`` apart, for d of 1, 2 or 4 within +/// one aligned group of eight, which a butterfly over the columns uses. +template +__device__ __forceinline__ constexpr int lane_col_stride(int d) { + return Tile::paired_columns && d > 1 ? 4 * d : d; +} + +template +__device__ __forceinline__ LaneOrigin lane_origin() { + const int warp = threadIdx.x / 32; + const int lane = threadIdx.x % 32; + return { + ((warp / Tile::warp_cols) * 4 + lane_row(lane)) * Tile::row_group, + ((warp % Tile::warp_cols) * 8 + lane_col(lane)) * 4}; +} + +/// Tile-local row of accumulator row ``i``. +template +__device__ __forceinline__ int accumulator_row(const LaneOrigin& o, int i) { + return o.row + (i / Tile::row_group) * Tile::row_stride + i % Tile::row_group; +} + +/// Tile-local column of the first accumulator of column quad ``g``. +template +__device__ __forceinline__ int accumulator_col(const LaneOrigin& o, int g) { + return o.col + g * Tile::col_stride; +} + +template +__device__ __forceinline__ float4 +accumulator_quad(const Accumulators& acc, int i, int g) { + return make_float4(acc[i][4 * g], acc[i][4 * g + 1], acc[i][4 * g + 2], + acc[i][4 * g + 3]); +} + +/// CTA tile of a one-dimensional grid: consecutive CTAs walk the column tiles +/// of one row tile, so they share their A rows while those are hot in L2. +struct TileIndex { + long row0; + int col0; +}; + +template +__device__ __forceinline__ TileIndex tile_index(int width) { + const int col_tiles = (width + Tile::cols - 1) / Tile::cols; + return {(long)(blockIdx.x / col_tiles) * Tile::rows, + (int)(blockIdx.x % col_tiles) * Tile::cols}; +} + +// --------------------------------------------------------------------------- +// Operand stagers. ``fetch(k0)`` issues the global loads of the slice +// [k0, k0 + Tile::depth) of the contraction axis, of length ``extent``, into +// registers and ``commit`` writes them to shared memory in the depth-major +// layout the fragments read. Depths past the extent are zero-filled; rows and +// columns past the matrix are clamped to its last row or column, whose finite +// values reach only accumulators that are never stored. +// --------------------------------------------------------------------------- + +/// Thread map of a ``kLines`` x depth slice read as float4 along depth and +/// stored depth-major. Lane pairs cover the 32-byte segment of one line in +/// each 8-deep group of the slice, so a warp reads 16 lines and its scalar +/// stores land on 32 distinct banks. +template +struct TransposedSlice { + static constexpr int count = kLines * Tile::depth / 4 / Tile::threads; + static_assert(count >= 1 && count * 4 * Tile::threads == kLines * Tile::depth, + "the threads must tile the slice evenly"); + static_assert(2 * kLines % 32 == 0, "a warp stays within one 8-deep group"); + __device__ static int line(int s) { + const int i = threadIdx.x + s * Tile::threads; + return (i / 2) % kLines; + } + __device__ static int quad(int s) { + const int i = threadIdx.x + s * Tile::threads; + return i % 2 + 2 * (i / (2 * kLines)); + } +}; + +template +__device__ __forceinline__ void store_transposed(float (*dst)[kLines + kSkew], + const float4 (&v)[kCount]) { + using Map = TransposedSlice; +#pragma unroll + for (int s = 0; s < kCount; ++s) { + const int q = 4 * Map::quad(s); + const int l = Map::line(s); + dst[q][l] = v[s].x; + dst[q + 1][l] = v[s].y; + dst[q + 2][l] = v[s].z; + dst[q + 3][l] = v[s].w; + } +} + +/// A operand read as stored from a row-major (nodes, K) tensor: the layer +/// input of the forward, or a dpre emitted for the backward. +template +struct InputStager; + +/// float4 loads, for 16-byte aligned rows. +template +struct InputStager { + using Map = TransposedSlice; + const float* src[Map::count]; + float4 v[Map::count]; + int extent; + + __device__ InputStager(const float* x, long row0, long nodes, int extent_) + : extent(extent_) { +#pragma unroll + for (int s = 0; s < Map::count; ++s) { + const long row = min(row0 + Map::line(s), nodes - 1); + src[s] = x + row * extent + 4 * Map::quad(s); + } + } + + __device__ __forceinline__ void fetch(int k0) { +#pragma unroll + for (int s = 0; s < Map::count; ++s) { + const int k = k0 + 4 * Map::quad(s); + v[s] = k < extent ? load4(src[s] + k0) : zero4(); + if (k + kLookahead * Tile::depth < extent) { + prefetch_l2(src[s] + k0 + kLookahead * Tile::depth); + } + } + } + + __device__ __forceinline__ void commit(float (*a)[Tile::rows + kSkew]) { + store_transposed(a, v); + } +}; + +/// Scalar loads, for any row stride: eight lanes cover the 32-byte segment of +/// one line and the warp's stores land on 32 distinct banks. +template +struct InputStager { + static constexpr int count = Tile::rows * Tile::depth / Tile::threads; + static_assert(count >= 1 && count * Tile::threads == Tile::rows * Tile::depth, + "the threads must tile the slice evenly"); + const float* src[count]; + float v[count]; + int extent; + + __device__ static int line(int s) { + const int i = threadIdx.x + s * Tile::threads; + return (i / 8) % Tile::rows; + } + __device__ static int col(int s) { + const int i = threadIdx.x + s * Tile::threads; + return i % 8 + 8 * (i / (8 * Tile::rows)); + } + + __device__ InputStager(const float* x, long row0, long nodes, int extent_) + : extent(extent_) { +#pragma unroll + for (int s = 0; s < count; ++s) { + const long row = min(row0 + line(s), nodes - 1); + src[s] = x + row * extent + col(s); + } + } + + __device__ __forceinline__ void fetch(int k0) { +#pragma unroll + for (int s = 0; s < count; ++s) { + const int k = k0 + col(s); + v[s] = k < extent ? __ldg(src[s] + k0) : 0.f; + if (k + kLookahead * Tile::depth < extent) { + prefetch_l2(src[s] + k0 + kLookahead * Tile::depth); + } + } + } + + __device__ __forceinline__ void commit(float (*a)[Tile::rows + kSkew]) { +#pragma unroll + for (int s = 0; s < count; ++s) { + a[col(s)][line(s)] = v[s]; + } + } +}; + +/// Forward B operand: the row-major (K, width) weight, read as float4 +/// along its output channels and stored as is. +template +struct WeightStager { + static constexpr int quads = Tile::cols / 4; + static constexpr int count = Tile::depth * quads / Tile::threads; + static_assert(count >= 1 && count * Tile::threads == Tile::depth * quads && + Tile::threads % quads == 0, + "the threads must tile the slice evenly"); + const float* src; + float4 v[count]; + int extent; + int width; + + __device__ static int line(int s) { + return (threadIdx.x + s * Tile::threads) / quads; + } + + __device__ WeightStager(const float* w, int col0, int extent_, int width_) + : src(w + min(col0 + 4 * (int)(threadIdx.x % quads), width_ - 4)), + extent(extent_), + width(width_) {} + + __device__ __forceinline__ void fetch(int k0) { +#pragma unroll + for (int s = 0; s < count; ++s) { + const int k = k0 + line(s); + v[s] = k < extent ? load4(src + (long)k * width) : zero4(); + } + } + + __device__ __forceinline__ void commit(float (*b)[Tile::cols + kSkew]) { +#pragma unroll + for (int s = 0; s < count; ++s) { + store4(&b[line(s)][4 * (threadIdx.x % quads)], v[s]); + } + } +}; + +/// Backward B operand: W^T for the row-major (width, K) weight W, read +/// as float4 along W's rows (the contraction axis) and stored transposed. +template +struct WeightTransposeStager { + using Map = TransposedSlice; + const float* src[Map::count]; + float4 v[Map::count]; + int extent; + + __device__ WeightTransposeStager(const float* w, + int col0, + int extent_, + int width) + : extent(extent_) { +#pragma unroll + for (int s = 0; s < Map::count; ++s) { + const int n = min(col0 + Map::line(s), width - 1); + src[s] = w + (long)n * extent + 4 * Map::quad(s); + } + } + + __device__ __forceinline__ void fetch(int k0) { +#pragma unroll + for (int s = 0; s < Map::count; ++s) { + v[s] = k0 + 4 * Map::quad(s) < extent ? load4(src[s] + k0) : zero4(); + } + } + + __device__ __forceinline__ void commit(float (*b)[Tile::cols + kSkew]) { + store_transposed(b, v); + } +}; + +// --------------------------------------------------------------------------- +// Main loop. Every accumulator sums the contraction axis in ascending order +// with one fused multiply-add per term, independent of the tile shape. +// --------------------------------------------------------------------------- + +template +__device__ __forceinline__ void multiply_slice( + const float (*a)[Tile::rows + kSkew], + const float (*b)[Tile::cols + kSkew], + const LaneOrigin& o, + Accumulators& acc) { +#pragma unroll + for (int k = 0; k < Tile::depth; ++k) { + float av[Tile::tm]; + float bv[Tile::tn]; +#pragma unroll + for (int h = 0; h < Tile::tm / Tile::row_group; ++h) { + const float* row = &a[k][o.row + h * Tile::row_stride]; + if constexpr (Tile::row_group == 4) { + const float4 v = lds4(row); + av[4 * h] = v.x; + av[4 * h + 1] = v.y; + av[4 * h + 2] = v.z; + av[4 * h + 3] = v.w; + } else { + const float2 v = lds2(row); + av[2 * h] = v.x; + av[2 * h + 1] = v.y; + } + } +#pragma unroll + for (int g = 0; g < Tile::tn / 4; ++g) { + const float4 v = lds4(&b[k][o.col + g * Tile::col_stride]); + bv[4 * g] = v.x; + bv[4 * g + 1] = v.y; + bv[4 * g + 2] = v.z; + bv[4 * g + 3] = v.w; + } +#pragma unroll + for (int i = 0; i < Tile::tm; ++i) { +#pragma unroll + for (int j = 0; j < Tile::tn; ++j) { + acc[i][j] = fmaf(av[i], bv[j], acc[i][j]); + } + } + } +} + +template +__device__ __forceinline__ void zero_accumulators(Accumulators& acc) { +#pragma unroll + for (int i = 0; i < S::tm; ++i) { +#pragma unroll + for (int j = 0; j < S::tn; ++j) { + acc[i][j] = 0.f; + } + } +} + +template +__device__ __forceinline__ void gemm_mainloop(GemmStorage& smem, + StagerA& sa, + StagerB& sb, + int extent, + const LaneOrigin& o, + Accumulators& acc) { + zero_accumulators(acc); + const int slices = (extent + Tile::depth - 1) / Tile::depth; + sa.fetch(0); + sb.fetch(0); + sa.commit(smem.a[0]); + sb.commit(smem.b[0]); + __syncthreads(); + for (int s = 0; s < slices; ++s) { + const int buf = s & 1; + sa.fetch((s + 1) * Tile::depth); + sb.fetch((s + 1) * Tile::depth); + multiply_slice(smem.a[buf], smem.b[buf], o, acc); + sa.commit(smem.a[buf ^ 1]); + sb.commit(smem.b[buf ^ 1]); + __syncthreads(); + } +} + +} // namespace deepmd_gemm diff --git a/source/tests/common/dpmodel/test_descriptor_dpa4c.py b/source/tests/common/dpmodel/test_descriptor_dpa4c.py index f75e3d859f..5378bb9756 100644 --- a/source/tests/common/dpmodel/test_descriptor_dpa4c.py +++ b/source/tests/common/dpmodel/test_descriptor_dpa4c.py @@ -12,6 +12,9 @@ import numpy as np import pytest +from deepmd.dpmodel.descriptor.dpa4_nn.mlp import ( + SwiGLUMLP, +) from deepmd.dpmodel.descriptor.dpa4c import ( DescrptDPA4C, ) @@ -33,6 +36,9 @@ from deepmd.dpmodel.utils.neighbor_graph import ( graph_from_dense_quartet, ) +from deepmd.dpmodel.utils.network import ( + NativeLayer, +) from deepmd.dpmodel.utils.nlist import ( extend_input_and_build_neighbor_list, ) @@ -150,6 +156,37 @@ def projected_blocks( ] +def randomize_attentions(descriptor: DescrptDPA4C) -> DescrptDPA4C: + """Draw every zero-initialized map of every further block. + + The output maps start at zero, which makes every block the identity, so a + contract tested at initialization would not reach the blocks. + """ + rng = np.random.default_rng(97) + for block in descriptor.attentions: + modules = [ + module + for value in vars(block).values() + for module in (value if isinstance(value, list) else [value]) + ] + for module in modules: + layers = module.layers if isinstance(module, SwiGLUMLP) else [module] + for layer in layers: + if isinstance(layer, NativeLayer) and not np.any(layer.w): + layer.w = rng.normal(size=layer.w.shape) + block.adam_field_gain = rng.normal(size=block.adam_field_gain.shape) + return descriptor + + +BLOCK_CONFIG = { + "ntypes": 2, + "channels": 32, + "lmax": 3, + "precision": "float64", + "seed": 61, +} + + class TestDPA4C: def setup_method(self) -> None: self.descriptor = DescrptDPA4C( @@ -541,6 +578,269 @@ def test_bispectrum_and_quartic_match_explicit_references( rtol=2e-13, ) + # === Further message-passing blocks === + + def test_further_block_is_the_identity_at_initialization(self) -> None: + single = DescrptDPA4C(rcut=3.0, **BLOCK_CONFIG) + multi_block = DescrptDPA4C(rcut=[3.0, 2.5], n_blocks=2, **BLOCK_CONFIG) + assert multi_block.get_dim_out() == single.get_dim_out() + # Every output map starts at zero, so every block reproduces the + # moments of the first. + np.testing.assert_allclose( + evaluate(multi_block), evaluate(single), atol=1e-14, rtol=0.0 + ) + + def test_further_blocks_are_o3_invariant_and_alter_the_descriptor(self) -> None: + single = DescrptDPA4C(rcut=3.0, **BLOCK_CONFIG) + multi_block = randomize_attentions( + DescrptDPA4C(rcut=[3.0, 2.5, 2.5], n_blocks=3, **BLOCK_CONFIG) + ) + reference = evaluate(multi_block) + assert np.max(np.abs(reference - evaluate(single))) > 1e-3 + rng = np.random.default_rng(61) + for determinant in (1.0, -1.0): + rotation, upper = np.linalg.qr(rng.normal(size=(3, 3))) + rotation = rotation * np.sign(np.diag(upper)) + if np.linalg.det(rotation) * determinant < 0.0: + rotation[:, 0] *= -1.0 + np.testing.assert_allclose( + evaluate(multi_block, COORD @ rotation.T), + reference, + atol=1e-11, + rtol=1e-11, + ) + + def test_block_attention_matches_the_explicit_terms(self) -> None: + descriptor = randomize_attentions( + DescrptDPA4C(rcut=[3.0, 2.0], n_blocks=2, **BLOCK_CONFIG) + ) + block = descriptor.attentions[0] + rng = np.random.default_rng(67) + n_node, n_edge, channels = 3, 7, 32 + heads = block.HEADS + moments = rng.normal(size=(n_node, descriptor.degree_offsets[-1])) + invariants = rng.normal(size=(n_node, block.descriptor_dim)) + direction = rng.normal(size=(n_edge, 3)) + direction /= np.linalg.norm(direction, axis=1, keepdims=True) + basis = build_angular_basis(direction, 3) + src = rng.integers(0, n_node, size=n_edge) + dst = rng.integers(0, n_node, size=n_edge) + amplitude = rng.normal(size=(n_edge, channels)) + envelope = rng.uniform(0.0, 1.0, size=n_edge) + block_envelope = rng.uniform(0.0, 1.0, size=n_edge) + rescaled, transport = block.call( + block.source_features(moments, invariants), + block.center_features(invariants), + amplitude, + basis, + envelope, + block_envelope, + src, + dst, + ) + + def saturate(value: np.ndarray, knee: float) -> np.ndarray: + return value / np.sqrt(1.0 + (value / knee) ** 2) + + # Every head of every degree of the source is saturated by its norm, + # and the fields read it along the reversed bond, which flips the + # sign of every odd degree. + keys, fields = [], [] + for degree, projection in enumerate(block.key_projections, start=1): + start, end = descriptor.degree_offsets[degree : degree + 2] + moment = moments[src, start:end].reshape( + n_edge, 2 * degree + 1, descriptor.degree_channels[degree] + ) + key = np.einsum("emc,ch->emh", moment, projection.w) + key /= np.sqrt( + 1.0 + np.sum(key**2, axis=1, keepdims=True) / block.KEY_KNEE**2 + ) + keys.append(key) + fields.append( + (-1.0) ** degree + * np.einsum("em,emh->eh", basis[:, degree**2 : (degree + 1) ** 2], key) + ) + keys = np.concatenate(keys, axis=1) + fields = np.stack(fields, axis=1) + state_input = saturate(invariants, block.STATE_KNEE)[src] + amplitude_input = saturate(amplitude, block.AMPLITUDE_KNEE) + field = np.einsum("elh,lh->eh", fields, block.adam_field_gain) + hidden = ( + block.hidden_state.call(state_input) + + block.hidden_field.call(fields.reshape(n_edge, -1)) + + block.hidden_amplitude.call(amplitude_input) + ) + logit = ( + field[:, np.arange(channels) % heads] + + block.state_encoder.call(state_input) + + block.hidden_output.call(hidden / (1.0 + np.exp(-hidden))) + ) + np.testing.assert_allclose( + rescaled, + amplitude * (1.0 + block_envelope[:, None] * np.tanh(logit)), + atol=1e-12, + rtol=1e-12, + ) + + # The keys reach the centers through an envelope-weighted softmax of + # the capped logits of the leading channels, with a null mass. + cap = block.LOGIT_CAP + mass = (envelope * block_envelope)[:, None] ** 2 * np.exp( + cap * np.tanh(logit[:, :heads] / cap) + ) + null = np.log1p( + np.exp(block.null_mass.call(saturate(invariants, block.STATE_KNEE))) + ) + denominator = null + block.NULL_FLOOR + numerator = np.zeros((n_node, keys.shape[1], heads)) + weight = mass * block.transport_radial.call(amplitude_input) + for edge in range(n_edge): + denominator[dst[edge]] += mass[edge] + numerator[dst[edge]] += weight[edge] * keys[edge] + reduced = numerator / denominator[:, None, :] + expected, start = [], 0 + for degree, output in enumerate(block.transport_outputs, start=1): + size = 2 * degree + 1 + expected.append( + np.einsum( + "nmh,hc->nmc", reduced[:, start : start + size], output.w + ).reshape(n_node, -1) + ) + start += size + np.testing.assert_allclose( + transport, np.concatenate(expected, axis=1), atol=1e-12, rtol=1e-12 + ) + + def test_block_factor_is_bounded_and_saturates_far_from_the_data( + self, + ) -> None: + descriptor = randomize_attentions( + DescrptDPA4C(rcut=[3.0, 2.0], n_blocks=2, **BLOCK_CONFIG) + ) + block = descriptor.attentions[0] + rng = np.random.default_rng(71) + moments = 1.0e6 * rng.normal(size=(4, descriptor.degree_offsets[-1])) + direction = rng.normal(size=(9, 3)) + direction /= np.linalg.norm(direction, axis=1, keepdims=True) + basis = build_angular_basis(direction, 3) + distance = np.linspace(0.5, 2.8, 9) + src = rng.integers(0, 4, size=9) + + def factor(invariants: np.ndarray) -> np.ndarray: + # The SiLU of the state encoder overflows its exponential at the + # largest inputs and saturates exactly, which is the limit tested. + with np.errstate(over="ignore"): + return block.call( + block.source_features(moments, invariants), + block.center_features(invariants), + np.ones((9, 32)), + basis, + np.ones(9), + descriptor.block_envelopes[0].call(distance), + src, + np.zeros(9, dtype=np.int64), + )[0] + + far = 1.0e6 * rng.normal(size=(4, block.descriptor_dim)) + value = factor(far) + # The factor lies in [0, 2] whatever its inputs, and equals one on + # every edge beyond the cutoff of the block. + assert value.shape == (9, 32) + assert np.all((value >= 0.0) & (value <= 2.0)) + np.testing.assert_array_equal(value[distance >= 2.0], 1.0) + + # The saturation acts per component: a component far beyond the knee + # loses its slope, while one near the data keeps it. + moments = np.zeros_like(moments) + near = 0.3 * rng.normal(size=(4, block.descriptor_dim)) + far = 100.0 * rng.normal(size=(4, block.descriptor_dim)) + + def slopes(invariants: np.ndarray) -> np.ndarray: + base = factor(invariants) + step = 1.0e-6 + result = [] + for component in range(block.descriptor_dim): + shifted = invariants.copy() + shifted[:, component] += step + result.append(np.max(np.abs(factor(shifted) - base)) / step) + return np.asarray(result) + + outside = np.all(np.abs(far) > 50.0, axis=0) + assert outside.sum() > 0 + assert slopes(far)[outside].max() < 1e-3 * slopes(near).mean() + + def test_further_block_reads_the_second_shell(self) -> None: + # Atom 2 lies within the cutoff of atom 1 only, so the descriptor of + # atom 0 sees it through the second block alone. + coord = np.array([[[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.9, 0.3, 0.0]]]) + moved = coord.copy() + moved[0, 2] += [0.0, 0.2, 0.1] + atype = np.zeros((1, 3), dtype=np.int64) + config = {**BLOCK_CONFIG, "ntypes": 1, "channels": 16, "lmax": 2} + single = DescrptDPA4C(rcut=2.5, **config) + multi_block = randomize_attentions( + DescrptDPA4C(rcut=[2.5, 2.5], n_blocks=2, **config) + ) + assert not single.has_message_passing() + assert multi_block.has_message_passing() + assert multi_block.has_message_passing_across_ranks() + + def change(descriptor: DescrptDPA4C) -> float: + return np.max( + np.abs( + evaluate(descriptor, moved, atype)[0, 0] + - evaluate(descriptor, coord, atype)[0, 0] + ) + ) + + assert change(single) == 0.0 + assert change(multi_block) > 1e-6 + + def test_multi_block_descriptor_roundtrips_and_rejects_invalid_cutoffs( + self, + ) -> None: + descriptor = randomize_attentions( + DescrptDPA4C(rcut=[3.0, 2.5, 2.0], n_blocks=3, **BLOCK_CONFIG) + ) + data = descriptor.serialize() + assert data["rcut"] == [3.0, 2.5, 2.0] + assert data["n_blocks"] == 3 + restored = DescrptDPA4C.deserialize(data) + assert restored.block_rcut == [3.0, 2.5, 2.0] + # One cutoff applies to every block and serializes as one value. + uniform = DescrptDPA4C(rcut=3.0, n_blocks=2, **BLOCK_CONFIG) + assert uniform.block_rcut == [3.0, 3.0] + assert uniform.serialize()["rcut"] == 3.0 + assert DescrptDPA4C.deserialize(uniform.serialize()).block_rcut == [3.0, 3.0] + # A record of format 2 carries one cutoff and one block. + legacy = DescrptDPA4C(rcut=3.0, **BLOCK_CONFIG).serialize() + legacy["@version"] = 2 + del legacy["attentions"], legacy["n_blocks"] + assert not DescrptDPA4C.deserialize(legacy).attentions + assert restored.get_rcut() == 3.0 + np.testing.assert_array_equal(evaluate(restored), evaluate(descriptor)) + single = DescrptDPA4C(rcut=3.0, **BLOCK_CONFIG).serialize() + assert single["rcut"] == 3.0 + assert not DescrptDPA4C.deserialize(single).attentions + with pytest.raises(ValueError, match="must not increase"): + DescrptDPA4C(rcut=[2.5, 3.0], n_blocks=2, **BLOCK_CONFIG) + for radius in (0.0, float("nan")): + with pytest.raises(ValueError, match="positive"): + DescrptDPA4C(rcut=[3.0, radius], n_blocks=2, **BLOCK_CONFIG) + with pytest.raises(ValueError, match=r"lists 2 cutoff\(s\)"): + DescrptDPA4C(rcut=[3.0, 2.5], n_blocks=3, **BLOCK_CONFIG) + with pytest.raises(ValueError, match=r"lists 2 cutoff\(s\)"): + DescrptDPA4C(rcut=[3.0, 2.5], **BLOCK_CONFIG) + for invalid in (0, 1.5, True): + with pytest.raises(ValueError, match="positive integer"): + DescrptDPA4C(rcut=3.0, n_blocks=invalid, **BLOCK_CONFIG) + # A record whose blocks disagree with its block count is rejected. + mismatched = descriptor.serialize() + mismatched["n_blocks"] = 2 + mismatched["rcut"] = [3.0, 2.5] + with pytest.raises(ValueError, match="further blocks"): + DescrptDPA4C.deserialize(mismatched) + def test_jax_lmax4_matches_numpy(self) -> None: pytest.importorskip("jax") from deepmd.jax.env import ( @@ -702,6 +1002,69 @@ def test_frozen_pair_equals_removed_edge(self, distance: float) -> None: assert np.abs(evaluate(self.plain, coord, atype) - windowed).max() > 1e-3 np.testing.assert_array_equal(windowed, evaluate(removed, coord, atype)) + def multi_block(self) -> DescrptDPA4C: + """Build a two-block windowed descriptor with random block maps.""" + return randomize_attentions( + DescrptDPA4C( + **{**self.config, "rcut": 3.0, "n_blocks": 2}, + inner_clamp_f_inner=self.R_INNER, + inner_clamp_f_outer=self.R_OUTER, + inner_clamp_scale="absolute", + ) + ) + + @pytest.mark.parametrize("distance", [0.05, 0.3, 0.5]) + def test_frozen_pair_does_not_leak_through_a_neighbor( + self, distance: float + ) -> None: + # Atoms 0 and 1 form a frozen pair. The second block would otherwise + # hand the view of a third atom, which sees both, back to atom 0. + descriptor = self.multi_block() + coord, atype = self.cluster(distance) + reference = evaluate(descriptor, coord, atype) + moved = coord.copy() + moved[0, 1] = distance * np.array([-0.6, 0.0, 0.8]) + perturbed = evaluate(descriptor, moved, atype) + # Moving atom 1 inside the frozen zone leaves atom 0 and every third + # atom unchanged, and the third atoms match the system without the + # pair. + unchanged = [0, 2, 3, 4] + np.testing.assert_allclose( + perturbed[0, unchanged], reference[0, unchanged], atol=1e-13, rtol=0.0 + ) + third = [2, 3, 4] + without = evaluate(descriptor, coord[:, third], atype[:, third]) + np.testing.assert_allclose( + reference[0, third], without[0], atol=1e-13, rtol=0.0 + ) + # Without a window atom 0 sees atom 1 through a third atom, so the + # contract is not vacuous. + plain = randomize_attentions( + DescrptDPA4C(**{**self.config, "rcut": 3.0, "n_blocks": 2}) + ) + assert ( + np.abs( + evaluate(plain, moved, atype)[0, 0] + - evaluate(plain, coord, atype)[0, 0] + ).max() + > 1e-6 + ) + + def test_frozen_pair_window_keeps_the_multi_block_descriptor_smooth(self) -> None: + descriptor = self.multi_block() + distances = np.linspace(self.R_INNER - 0.02, self.R_OUTER + 0.02, 97) + probe = [] + for distance in distances: + coord, atype = self.cluster(float(distance)) + # Atom 1 moves; every other atom stops depending on it inside the + # frozen zone. + probe.append(evaluate(descriptor, coord, atype)[0, [0, 2, 3, 4]].sum()) + probe = np.asarray(probe) + inner = distances <= self.R_INNER + np.testing.assert_allclose(probe[inner], probe[inner][0], atol=1e-12) + third = np.diff(probe, n=3) + assert np.abs(third).max() < 1e-2 * np.abs(probe).max() + def test_pairs_beyond_the_window_are_unchanged(self) -> None: coord, atype = self.cluster(self.R_OUTER) np.testing.assert_array_equal( @@ -779,7 +1142,7 @@ def test_edge_inside_the_window_reads_the_clamped_length( def test_serialization_roundtrip_keeps_the_window(self) -> None: coord, atype = self.cluster(0.65) data = self.windowed.serialize() - assert data["@version"] == 2 + assert data["@version"] == 3 assert data["inner_clamp_f_inner"] == self.R_INNER assert data["inner_clamp_f_outer"] == self.R_OUTER assert data["inner_clamp_scale"] == "absolute" @@ -845,6 +1208,12 @@ def test_configuration_boundaries( DescrptDPA4C(**{"rcut": 3.0, "ntypes": 1, **config}) +def test_legacy_positional_use_amp_keeps_its_parameter_slot() -> None: + descriptor = DescrptDPA4C(3.0, 2, 8, 2, "bessel", 4, 0, False) + assert descriptor.n_blocks == 1 + assert descriptor.use_amp is False + + @pytest.mark.parametrize("neighbors", [8, 4096]) def test_neighbor_statistics_report_distance_without_deriving_a_capacity( neighbors: int, @@ -970,11 +1339,14 @@ def make_spin_descriptor(**overrides: Any) -> DescrptDPA4C: @pytest.mark.parametrize("precision", ["float32", "float64"]) @pytest.mark.parametrize("channels", [8, 32]) @pytest.mark.parametrize("node_count", [0, 2]) +@pytest.mark.parametrize("n_blocks", [1, 2]) def test_native_spin_graph_without_edges( - precision: str, channels: int, node_count: int + precision: str, channels: int, node_count: int, n_blocks: int ) -> None: """Both zero-node graphs and isolated atoms retain the feature width.""" - descriptor = make_spin_descriptor(precision=precision, channels=channels) + descriptor = make_spin_descriptor( + precision=precision, channels=channels, n_blocks=n_blocks + ) graph = neighbor_graph.NeighborGraph( n_node=np.array([node_count], dtype=np.int64), n_local=np.array([node_count], dtype=np.int64), @@ -1218,6 +1590,40 @@ def test_time_reversal_is_exact(self) -> None: self.evaluate(-self.spin), ) + def test_further_block_carries_the_spin_moments(self) -> None: + multi_block = make_spin_descriptor(rcut=[3.0, 2.5], n_blocks=2) + np.testing.assert_allclose( + multi_block.call_graph(self.graph, self.atype, spin=self.spin)[0], + self.evaluate(self.spin), + atol=1e-14, + rtol=0.0, + ) + randomize_attentions(multi_block) + reference = multi_block.call_graph(self.graph, self.atype, spin=self.spin)[0] + assert np.abs(reference - self.evaluate(self.spin)).max() > 1e-3 + # The state reads the spin invariants, which have even spin order, so + # the multi-block descriptor keeps time reversal and axial O(3) symmetry. + assert multi_block.attentions[0].descriptor_dim == multi_block.get_dim_out() + np.testing.assert_array_equal( + multi_block.call_graph(self.graph, self.atype, spin=-self.spin)[0], + reference, + ) + rng = np.random.default_rng(13) + orthogonal, triangular = np.linalg.qr(rng.normal(size=(3, 3))) + orthogonal = -orthogonal * np.sign(np.diag(triangular)) + rotated = neighbor_graph.build_neighbor_graph( + SPIN_COORD @ orthogonal.T, SPIN_ATYPE, None, multi_block.get_rcut() + ) + np.testing.assert_allclose( + multi_block.call_graph( + rotated, + self.atype, + spin=(self.spin @ orthogonal.T) * np.linalg.det(orthogonal), + )[0], + reference, + atol=1e-12, + ) + def test_non_magnetic_types_are_ignored_bitwise(self) -> None: # The per-type gate is multiplicative, so a non-magnetic atom has no # spin degree of freedom at any derivative order rather than merely a diff --git a/source/tests/common/dpmodel/test_lmdb_data.py b/source/tests/common/dpmodel/test_lmdb_data.py index 27b4c90cdd..7178d41abc 100644 --- a/source/tests/common/dpmodel/test_lmdb_data.py +++ b/source/tests/common/dpmodel/test_lmdb_data.py @@ -177,10 +177,12 @@ def _create_mix_probe_lmdb(path: str) -> str: """Create an LMDB whose frame-level fields collide in shape with the atom axis. Frames alternate between 2 and 9 atoms and carry a two-component - ``fparam`` alongside a nine-component ``virials``. A padding rule that + ``fparam`` alongside a nine-component ``virials``, and a two-component + ``homo_energy`` that no requirement declares. A padding rule that guessed the atom axis from a leading dimension would misclassify - ``fparam`` on the 2-atom frames and ``virials`` on the 9-atom ones, so this - fixture pins the classification down to the exact ambiguous shapes. + ``fparam`` and ``homo_energy`` on the 2-atom frames and ``virials`` on the + 9-atom ones, so this fixture pins the classification down to the exact + ambiguous shapes. """ nlocs = [2, 9, 2, 9, 2, 9] rng = np.random.RandomState(7) @@ -205,6 +207,11 @@ def _create_mix_probe_lmdb(path: str) -> str: "shape": (2,), "data": rng.randn(2).astype(np.float64).tobytes(), } + frame["homo_energy"] = { + "type": " None: "ultra", ), ("dpa4c", "v20260901"): ("nano", "mini", "neo", "air", "plus"), - ("dpa4c", "v20260911"): ("nano", "mini", "neo", "air", "plus"), + ("dpa4c", "v20260911"): ( + "nano", + "mini", + "neo", + "air", + "plus", + "mini-duo", + "neo-duo", + "air-duo", + "plus-duo", + ), } assert set(MODEL_PRESETS) == { f"{family}-{grade}-{version}" @@ -193,6 +203,14 @@ def test_version_descriptor_options(family: str, version: str, options: dict) -> assert {key: descriptor[key] for key in options} == options +@pytest.mark.parametrize("grade", ["mini", "neo", "air", "plus"]) +def test_duo_preset_adds_one_block_to_its_grade(grade: str) -> None: + single = get_model_preset(f"dpa4c-{grade}-v20260911") + duo = get_model_preset(f"dpa4c-{grade}-duo-v20260911") + assert duo["descriptor"] == {**single["descriptor"], "n_blocks": 2} + assert duo["fitting_net"] == single["fitting_net"] + + def test_presets_carry_no_runtime_options() -> None: for name, preset in MODEL_PRESETS.items(): for region in ("descriptor", "fitting_net"): diff --git a/source/tests/infer/gen_dpa4c_canonical.py b/source/tests/infer/gen_dpa4c_canonical.py index 0351fd94d1..bec174335b 100644 --- a/source/tests/infer/gen_dpa4c_canonical.py +++ b/source/tests/infer/gen_dpa4c_canonical.py @@ -14,20 +14,31 @@ state applied at run time, and check the host entry points against the references written here. -Both descriptors are charge-conditioned, so each archive carries the rebuild -of its frozen tables that ``set_charge_spin`` runs. The compressed operators -are fp32 CUDA kernels, so the fixtures are generated only where the suite -has a GPU. +The single-block descriptors are charge-conditioned and carry the rebuild of +their frozen tables that ``set_charge_spin`` runs. Two-block counterparts +without conditioning exercise halo exchange in the C/C++ and Kokkos suites. +The compressed operators are fp32 CUDA kernels, so the fixtures are generated +only where the suite has a GPU. """ +from __future__ import ( + annotations, +) + import copy import json import os import sys import zipfile +from typing import ( + TYPE_CHECKING, +) import numpy as np +if TYPE_CHECKING: + import torch + # The gen scripts run standalone, outside pytest's package machinery, so the # relative imports the test suite uses do not apply here. sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) @@ -106,14 +117,29 @@ _SPIN_REDRAW_SCALE = 0.3 -def _compress(model): +def _compress(model: torch.nn.Module) -> torch.nn.Module: """Compress the descriptor of ``model`` as a deployment does.""" descriptor = model.atomic_model.fused_decomposition()[0].descriptor descriptor.enable_compression(1.4, table_stride_1=0.01) return model -def _build_model(): +def _activate_zero_parameters(module: torch.nn.Module, seed: int) -> None: + """Open zero-initialized maps so the spin and message-passing paths contribute.""" + import torch + + generator = torch.Generator(device="cpu").manual_seed(seed) + with torch.no_grad(): + for parameter in module.parameters(): + if parameter.numel() == 0 or bool((parameter != 0).any()): + continue + values = _SPIN_REDRAW_SCALE * torch.randn( + parameter.shape, generator=generator, dtype=torch.float64 + ) + parameter.copy_(values.to(dtype=parameter.dtype, device=parameter.device)) + + +def _build_model(n_blocks: int = 1, charge_conditioned: bool = True) -> torch.nn.Module: """Build, charge-activate and compress the energy model.""" import torch @@ -121,49 +147,50 @@ def _build_model(): get_model, ) - model = get_model(copy.deepcopy(CANONICAL_CONFIG)).eval() + config = copy.deepcopy(CANONICAL_CONFIG) + config["descriptor"].update(n_blocks=n_blocks, add_chg_spin_ebd=charge_conditioned) + model = get_model(config).eval() descriptor = model.atomic_model.fused_decomposition()[0].descriptor + for block in descriptor.attentions: + _activate_zero_parameters(block, _HEAD_SEED) # The projection of the charge-state head is zero initialized, which # would make the state unobservable and every comparison between states # vacuous. - head = descriptor.charge_spin_embedding.network.layers[-1] - generator = torch.Generator(device=head.w.device).manual_seed(_HEAD_SEED) - with torch.no_grad(): - head.w.copy_( - 0.5 - * torch.randn( - head.w.shape, - dtype=head.w.dtype, - device=head.w.device, - generator=generator, + if charge_conditioned: + head = descriptor.charge_spin_embedding.network.layers[-1] + generator = torch.Generator(device=head.w.device).manual_seed(_HEAD_SEED) + with torch.no_grad(): + head.w.copy_( + 0.5 + * torch.randn( + head.w.shape, + dtype=head.w.dtype, + device=head.w.device, + generator=generator, + ) ) - ) return _compress(model) -def _build_spin_model(): +def _build_spin_model( + n_blocks: int = 1, charge_conditioned: bool = True +) -> torch.nn.Module: """Build the native-spin model, open its zero parameters and compress it.""" - import torch - from deepmd.pt_expt.model.get_model import ( get_model, ) - model = get_model(copy.deepcopy(SPIN_CONFIG)).eval() - generator = torch.Generator(device="cpu").manual_seed(_SPIN_REDRAW_SEED) - with torch.no_grad(): - for parameter in model.parameters(): - if parameter.numel() == 0 or bool((parameter != 0).any()): - continue - values = _SPIN_REDRAW_SCALE * torch.randn( - parameter.shape, generator=generator, dtype=torch.float64 - ) - parameter.copy_(values.to(dtype=parameter.dtype, device=parameter.device)) + config = copy.deepcopy(SPIN_CONFIG) + config["descriptor"].update(n_blocks=n_blocks, add_chg_spin_ebd=charge_conditioned) + model = get_model(config).eval() + _activate_zero_parameters(model, _SPIN_REDRAW_SEED) return _compress(model) -def _check_metadata(pt2_path: str, spin: bool) -> None: - """Assert the archive is the compact canonical lower with a charge state.""" +def _check_metadata( + pt2_path: str, spin: bool, n_blocks: int, charge_conditioned: bool +) -> None: + """Check the canonical ABI, halo capability and optional charge-state rebuild.""" with zipfile.ZipFile(pt2_path) as zf: md = json.loads(zf.read("model/extra/metadata.json").decode("utf-8")) names = zf.namelist() @@ -187,25 +214,30 @@ def _check_metadata(pt2_path: str, spin: bool) -> None: ) assert md["lower_input_kind"] == "dpa4c_canonical" assert md["do_atomic_virial"] is True + assert md["has_message_passing"] is (n_blocks > 1) + assert md["has_comm_artifact"] is False + assert not any(name.endswith("forward_lower_with_comm.pt2") for name in names) # The compact canonical lower takes no condition per call; the state is # frozen into its tables, which ``set_charge_spin`` rebuilds. Without the # rebuild a runtime charge state cannot be served, and the C++ cases built # on it would not reach the replay. - assert md.get("charge_state_constants"), ( - "the archive carries no charge-state rebuild" - ) - assert any(name.endswith("charge_state.pt2") for name in names) + if charge_conditioned: + assert md.get("charge_state_constants"), ( + "the archive carries no charge-state rebuild" + ) + assert any(name.endswith("charge_state.pt2") for name in names) if spin: # The dispatch serves a native-spin archive without a with-comm # artifact through NativeSpinPTExpt, whose device entry is the one # the spin cases reach. assert md["spin_scheme"] == "native" - assert md.get("has_comm_artifact") is False assert "force_mag" in md["output_keys"] -def _write_ref(pt2_path: str, ref_path: str, spin: bool) -> None: - """Evaluate the archive under both states and write the C++ sidecar.""" +def _write_ref( + pt2_path: str, ref_path: str, spin: bool, charge_conditioned: bool +) -> None: + """Write the C++ reference, including both states of a conditioned archive.""" from deepmd.infer import ( DeepPot, ) @@ -222,10 +254,12 @@ def _write_ref(pt2_path: str, ref_path: str, spin: bool) -> None: system["spin"] = _SPINS[0] sections = {"system": system} energies = {} - for name, charge_spin in ( - ("default_state", _DEFAULT_CHG_SPIN), - ("other_state", _OTHER_CHG_SPIN), - ): + states = ( + (("default_state", _DEFAULT_CHG_SPIN), ("other_state", _OTHER_CHG_SPIN)) + if charge_conditioned + else (("default_state", None),) + ) + for name, charge_spin in states: if spin: e, f, v, ae, av, fm, _ = dp.eval( _COORDS, @@ -261,10 +295,11 @@ def _write_ref(pt2_path: str, ref_path: str, spin: bool) -> None: ) sections[name]["expected_fm"] = fm[0] # The C++ cases compare evaluations under the two states with each other. - assert abs(energies["other_state"] - energies["default_state"]) > 1e-4, ( - "the two charge states must differ, or a replay that kept the " - "constants of the first state would still match" - ) + if charge_conditioned: + assert abs(energies["other_state"] - energies["default_state"]) > 1e-4, ( + "the two charge states must differ, or a replay that kept the " + "constants of the first state would still match" + ) write_expected_ref( ref_path, sections=sections, @@ -273,7 +308,7 @@ def _write_ref(pt2_path: str, ref_path: str, spin: bool) -> None: print(f"Wrote {ref_path}") # noqa: T201 -def main(): +def main() -> None: from deepmd.pt_expt.utils.serialization import ( deserialize_to_file as pt_expt_deserialize_to_file, ) @@ -282,21 +317,25 @@ def main(): load_custom_ops() base_dir = os.path.dirname(__file__) - for stem, build, spin in ( - ("deeppot_dpa4c_canonical", _build_model, False), - ("deeppot_dpa4c_canonical_spin", _build_spin_model, True), + for stem, build, spin, n_blocks, conditioned in ( + ("deeppot_dpa4c_canonical", _build_model, False, 1, True), + ("deeppot_dpa4c_canonical_spin", _build_spin_model, True, 1, True), + ("deeppot_dpa4c_canonical_multiblock", _build_model, False, 2, False), + ("deeppot_dpa4c_canonical_spin_multiblock", _build_spin_model, True, 2, False), ): pt2_path = os.path.join(base_dir, f"{stem}.pt2") print(f"Exporting to {pt2_path} (lower_kind='dpa4c_canonical') ...") # noqa: T201 pt_expt_deserialize_to_file( pt2_path, - {"model": build().serialize()}, + {"model": build(n_blocks, conditioned).serialize()}, lower_kind="dpa4c_canonical", do_atomic_virial=True, ) print("Export done.") # noqa: T201 - _check_metadata(pt2_path, spin) - _write_ref(pt2_path, os.path.join(base_dir, f"{stem}.expected"), spin) + _check_metadata(pt2_path, spin, n_blocks, conditioned) + _write_ref( + pt2_path, os.path.join(base_dir, f"{stem}.expected"), spin, conditioned + ) print("\nDone!") # noqa: T201 diff --git a/source/tests/pt/test_compile_compat.py b/source/tests/pt/test_compile_compat.py index f33796c739..9710302dcb 100644 --- a/source/tests/pt/test_compile_compat.py +++ b/source/tests/pt/test_compile_compat.py @@ -44,6 +44,7 @@ def test_fusion_size_defaults_to_eight(monkeypatch) -> None: assert inference_options["cpp.min_chunk_size"] == 1 assert inference_options["cpp.dynamic_threads"] is True assert "cpp.max_horizontal_fusion_size" not in inference_options + assert "cpp.simdlen" not in inference_options def test_torch_211_inference_keeps_default_cpp_parallelism(monkeypatch) -> None: @@ -54,9 +55,8 @@ def test_torch_211_inference_keeps_default_cpp_parallelism(monkeypatch) -> None: assert "cpp.min_chunk_size" not in inference_options assert "cpp.dynamic_threads" not in inference_options - assert inference_options["cpp.max_horizontal_fusion_size"] == 1 - assert "cpp.simdlen" not in inference_options - assert "cpp.max_horizontal_fusion_size" not in build_inductor_compile_options() + assert inference_options["cpp.simdlen"] == 1 + assert "cpp.simdlen" not in build_inductor_compile_options() def test_inductor_kernels_write_separate_output_buffers() -> None: diff --git a/source/tests/pt_expt/descriptor/test_dpa4c.py b/source/tests/pt_expt/descriptor/test_dpa4c.py index eaa3b539a6..0eb5cfe1f7 100644 --- a/source/tests/pt_expt/descriptor/test_dpa4c.py +++ b/source/tests/pt_expt/descriptor/test_dpa4c.py @@ -29,8 +29,9 @@ ) # Structural variants exercised by the backend-agnostic contracts. They span -# both angular profiles and both radial function classes, and one bridging -# window whose transition zone holds several pairs of the test cluster. +# both angular profiles and both radial function classes, one bridging window +# whose transition zone holds several pairs of the test cluster, and two and +# three message-passing blocks with and without that window. STRUCTURES = [ {"channels": 16, "lmax": 2, "radial_modes": 0}, {"channels": 32, "lmax": 4, "radial_modes": 0}, @@ -44,9 +45,61 @@ "inner_clamp_f_outer": 1.25, "inner_clamp_scale": "absolute", }, + {"channels": 16, "lmax": 3, "radial_modes": 3, "rcut": [3.0, 2.5], "n_blocks": 2}, + { + "channels": 16, + "lmax": 3, + "radial_modes": 3, + "rcut": [3.0, 2.5], + "n_blocks": 2, + "inner_clamp_f_inner": 1.0, + "inner_clamp_f_outer": 1.25, + "inner_clamp_scale": "absolute", + }, + { + "channels": 16, + "lmax": 3, + "radial_modes": 3, + "rcut": 3.0, + "n_blocks": 3, + }, ] +def test_soft_saturation_preserves_float16_values_and_derivatives() -> None: + from deepmd.dpmodel.descriptor.dpa4c_nn.attention import ( + soft_saturate, + ) + from deepmd.pt_expt.kernels.dpa4c.attention import ( + _soft_saturate, + ) + + for saturate in (soft_saturate, _soft_saturate): + value = torch.tensor( + [-65504.0, -600.0, -2.0, -1.0, 0.0, 1.0, 2.0, 600.0, 65504.0], + dtype=torch.float16, + device=env.DEVICE, + requires_grad=True, + ) + result = saturate(value, 2.0) + (first,) = torch.autograd.grad(result.sum(), value, create_graph=True) + (second,) = torch.autograd.grad(first.sum(), value) + reference = value.detach().double().requires_grad_(True) + expected = reference / torch.sqrt(1.0 + (reference / 2.0) ** 2) + (expected_first,) = torch.autograd.grad( + expected.sum(), reference, create_graph=True + ) + (expected_second,) = torch.autograd.grad(expected_first.sum(), reference) + for actual, target in zip( + (result, first, second), + (expected, expected_first, expected_second), + strict=True, + ): + torch.testing.assert_close( + actual, target.to(torch.float16), rtol=3e-3, atol=5e-4 + ) + + class TestDPA4C: def setup_method(self) -> None: self.descriptor = self.build() @@ -77,18 +130,32 @@ def build(**structure: Any) -> DescrptDPA4C: Mixed-precision tests must override it, because CUDA autocast ignores double operands and would otherwise leave the region untouched. """ - return DescrptDPA4C( - rcut=3.0, + descriptor = DescrptDPA4C( ntypes=2, n_radial=4, seed=17, **{ + "rcut": 3.0, "channels": 16, "lmax": 2, "precision": "float64", **structure, }, ).to(env.DEVICE) + # The output maps of the further blocks start at zero, which makes + # every block the identity, so the contracts would not reach them. + # Every zero map is drawn at random to exercise the blocks. + generator = torch.Generator().manual_seed(17) + with torch.no_grad(): + for block in descriptor.attentions: + for weight in block.parameters(): + if not torch.any(weight): + weight.copy_( + torch.randn( + weight.shape, generator=generator, dtype=weight.dtype + ).to(weight.device) + ) + return descriptor def _inputs( self, @@ -254,6 +321,60 @@ def test_compression_round_trip_preserves_frozen_descriptor(self) -> None: self._evaluate(restored, self.coord), reference, rtol=1.3e-6, atol=1e-5 ) + def test_compressed_fallback_keeps_the_applied_charge_state(self) -> None: + descriptor = self.build( + precision="float32", + n_blocks=2, + add_chg_spin_ebd=True, + default_chg_spin=[0.0, 1.0], + ).eval() + head = descriptor.charge_spin_embedding.network.layers[-1] + with torch.no_grad(): + head.w.fill_(0.1) + reference = ( + DescrptDPA4C.deserialize(descriptor.serialize()).to(env.DEVICE).eval() + ) + reference.default_chg_spin = [2.0, 3.0] + expected = self._evaluate(reference, self.coord) + assert not torch.allclose(expected, self._evaluate(descriptor, self.coord)) + descriptor.enable_compression(0.5) + descriptor.apply_charge_state([2.0, 3.0]) + restored = ( + DescrptDPA4C.deserialize(descriptor.serialize()).to(env.DEVICE).eval() + ) + for candidate in (descriptor, restored): + assert candidate.get_default_chg_spin() == [2.0, 3.0] + # The descriptor computes in fp32 before the dense ABI casts its output. + torch.testing.assert_close( + self._evaluate(candidate, self.coord), expected, rtol=1.3e-6, atol=1e-5 + ) + coord, atype, mapping, nlist = self._inputs(self.coord) + actual = candidate( + coord, + atype, + nlist, + mapping=mapping, + charge_spin=torch.tensor([[0.0, 1.0]], device=env.DEVICE), + )[0] + torch.testing.assert_close(actual, expected, rtol=1.3e-6, atol=1e-5) + + def test_complete_source_neighborhoods_do_not_require_ownership(self) -> None: + descriptor = self.build(n_blocks=2).eval() + coord, atype, mapping, nlist = self._inputs(self.coord) + graph, atype = graph_from_dense_quartet(coord, atype, nlist, mapping) + reference, _ = descriptor.call_graph(graph, atype) + subset = dataclasses.replace(graph, n_local=graph.n_node - 1) + actual, _ = descriptor.call_graph(subset, atype) + # CUDA node reductions may accumulate the same edges in another order. + torch.testing.assert_close(actual, reference, atol=1e-12, rtol=1e-12) + + def test_dense_adapter_rejects_cross_rank_communication(self) -> None: + descriptor = self.build(n_blocks=2).eval() + coord, atype, mapping, nlist = self._inputs(self.coord) + assert not descriptor.dense_lower_supports_comm() + with pytest.raises(NotImplementedError, match="graph lower"): + descriptor(coord, atype, nlist, mapping=mapping, comm_dict={}) + def test_serialization_preserves_parameters(self) -> None: restored = DescrptDPA4C.deserialize(self.descriptor.serialize()).to(env.DEVICE) original_parameters = dict(self.descriptor.named_parameters()) @@ -359,6 +480,12 @@ def test_force_loss_double_backward(self, structure: dict[str, int]) -> None: create_graph=True, ) named_parameters = list(descriptor.named_parameters()) + registered = dict(named_parameters) + for index, block in enumerate(descriptor.attentions): + name = f"attentions.{index}.adam_field_gain" + assert name in registered + assert registered[name] is block.adam_field_gain + assert registered[name].requires_grad parameter_gradients = torch.autograd.grad( force_gradient.square().mean(), tuple(parameter for _, parameter in named_parameters), @@ -471,6 +598,22 @@ def test_cutoff_is_c3_continuous(self) -> None: assert inside[2].abs() < 2e-8 assert inside[3].abs() < 5e-4 + def test_block_cutoff_is_c3_continuous(self) -> None: + """The factor of a further block relaxes to one at its own cutoff.""" + descriptor = self.build(channels=16, lmax=3, rcut=[3.0, 2.0], n_blocks=2).eval() + single = self.build(channels=16, lmax=3).eval() + below = self._dimer_derivatives(descriptor, 2.0 - 1.0e-5) + boundary = self._dimer_derivatives(descriptor, 2.0) + beyond = self._dimer_derivatives(descriptor, 2.0 + 1.0e-5) + reference = self._dimer_derivatives(single, 2.0 + 1.0e-5) + # Beyond the block cutoff the descriptor is the single-block one, and + # the value and first three derivatives join it continuously. + for order in range(4): + torch.testing.assert_close(beyond[order], reference[order]) + torch.testing.assert_close( + boundary[order], below[order], atol=2e-4, rtol=0.0 + ) + def test_cutoff_edge_matches_removed_topology(self) -> None: descriptor = self.build().eval() radius = torch.tensor( @@ -554,12 +697,16 @@ def test_coincident_edge_has_finite_third_derivative(self) -> None: @pytest.mark.parametrize("precision", ["float32", "float64"]) @pytest.mark.parametrize("channels", [8, 32]) @pytest.mark.parametrize("node_count", [0, 2]) +@pytest.mark.parametrize("n_blocks", [1, 2]) def test_native_spin_graph_without_edges( - precision: str, channels: int, node_count: int + precision: str, channels: int, node_count: int, n_blocks: int ) -> None: """The reference spin path supports zero nodes as well as isolated atoms.""" descriptor = TestDPA4C.build( - precision=precision, channels=channels, use_spin=[True, False] + precision=precision, + channels=channels, + n_blocks=n_blocks, + use_spin=[True, False], ).eval() with torch.no_grad(): descriptor.spin.spin_gate.fill_(1.0) @@ -770,6 +917,28 @@ def test_mixed_precision_never_engages(self) -> None: for layer in self.descriptor.radial_embedding.layers: assert layer.autocast_output is False + def test_compression_packs_further_blocks(self) -> None: + """A descriptor with further blocks compresses, one record per block.""" + from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( + compression_ineligibility_reason, + mega_eligible, + ) + + descriptor = DescrptDPA4C( + rcut=[3.0, 2.5], + n_blocks=2, + ntypes=2, + channels=8, + lmax=2, + n_radial=4, + precision="float32", + seed=23, + ).to(env.DEVICE) + assert mega_eligible(descriptor) + assert compression_ineligibility_reason(descriptor) is None + descriptor.enable_compression(0.5) + assert descriptor.compress_blocks.shape[0] == 1 + def test_compression_covers_the_spin_families(self) -> None: """Spin follows the degree profile, so compression covers it. diff --git a/source/tests/pt_expt/descriptor/test_dpa4c_cpu.py b/source/tests/pt_expt/descriptor/test_dpa4c_cpu.py index 840da0dc4f..9703263e7e 100644 --- a/source/tests/pt_expt/descriptor/test_dpa4c_cpu.py +++ b/source/tests/pt_expt/descriptor/test_dpa4c_cpu.py @@ -18,6 +18,7 @@ import torch from deepmd.dpmodel.utils.neighbor_graph import ( + NeighborGraph, attach_edge_csr, graph_from_dense_quartet, ) @@ -30,7 +31,9 @@ from deepmd.pt_expt.kernels.dpa4c.graph_compress import ( _portable_inputs, _radial_knots, + _reference_backward, _reference_descriptor, + _reference_forward, build_compression_artifacts, build_low_rank_table, build_radial_table, @@ -129,9 +132,13 @@ def test_fixed_basis_types_freeze_the_basis() -> None: def test_adam_route_patterns_name_the_first_radial_layer() -> None: - """The descriptor routes the layer that reads the radial basis to AdamW.""" + """The descriptor routes the layer that reads the radial basis to AdamW. + + The attention of a multi-block descriptor stays on the default route. + """ descriptor = DescrptDPA4C( - rcut=3.0, + rcut=[3.0, 2.5], + n_blocks=2, ntypes=2, channels=8, lmax=2, @@ -906,6 +913,47 @@ def test_empty_graph_produces_the_isolated_atom_descriptor() -> None: torch.testing.assert_close(state[:, 1], torch.full_like(state[:, 1], 0.5)) +@pytest.mark.parametrize("node_count", [0, 2]) +def test_empty_multiblock_reference_preserves_feature_width(node_count: int) -> None: + """Zero-edge graphs retain the declared node and feature axes through backward.""" + descriptor = _build_descriptor(8, n_blocks=2).cpu() + counts = torch.tensor([node_count], dtype=torch.int64, device="cpu") + order = torch.empty(0, dtype=torch.int64, device="cpu") + rows = torch.zeros(node_count + 1, dtype=torch.int64, device="cpu") + graph = NeighborGraph( + n_node=counts, + n_local=counts, + edge_index=torch.empty(2, 0, dtype=torch.int64, device="cpu"), + edge_vec=torch.empty(0, 3, dtype=torch.float32, device="cpu"), + edge_mask=torch.empty(0, dtype=torch.bool, device="cpu"), + destination_order=order, + destination_row_ptr=rows, + source_order=order, + source_row_ptr=rows, + ) + atype = torch.arange(node_count, dtype=torch.int64, device="cpu") % 2 + expected, _ = descriptor.call_graph(graph, atype) + artifacts = build_compression_artifacts(descriptor) + arguments = _arguments(descriptor, graph, atype) + output, state = _reference_forward( + graph.edge_vec, *arguments, blocks_record=artifacts["blocks"] + ) + assert output.shape == (node_count, descriptor.get_dim_out()) + torch.testing.assert_close(output, expected) + gradients = _reference_backward( + torch.ones_like(output), + state, + graph.edge_vec, + *arguments, + graph.edge_vec.new_empty(0), + graph.edge_vec.new_empty(0), + blocks_record=artifacts["blocks"], + ) + assert gradients[0].shape == (0, 3) + for gradient in gradients: + assert torch.isfinite(gradient).all() + + def _restrict_scalar_rank(descriptor: DescrptDPA4C, rank: int) -> None: """Confine the scalar-only radial channels to a span of ``rank`` functions. diff --git a/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py b/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py index 307ebd8f15..20b24c9c51 100644 --- a/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py +++ b/source/tests/pt_expt/descriptor/test_dpa4c_cuda.py @@ -3006,12 +3006,14 @@ def _fused_arguments( atom_bias: torch.Tensor, spin: torch.Tensor | None = None, pair_table: torch.Tensor | None = None, + border: Any = None, ) -> list[Any]: """Return the arguments with which the fused wrapper calls the operator. The call is recorded rather than evaluated. The CPU reference of the operator is registered first, so that the arguments can be evaluated on - either device. + either device. ``border`` is the border plan of a node set with halo rows, + which a descriptor of several blocks reads. """ from deepmd.pt_expt.kernels.dpa4c import ( canonical, @@ -3026,7 +3028,14 @@ def _fused_arguments( lambda *arguments: calls.append(list(arguments)), ) canonical.dpa4c_canonical_compress_energy_force( - descriptor, fitting, graph, atype, atom_bias, spin, pair_table + descriptor, + fitting, + graph, + atype, + atom_bias, + spin, + pair_table, + border=border, ) (arguments,) = calls return arguments @@ -4088,11 +4097,16 @@ def _frozen_route_kernels(directory: str) -> dict[str, Any]: lower_kind="dpa4c_canonical", do_atomic_virial=True, ) - # The table is the last argument of the schema; a call that leaves it - # to its default of no table records one argument fewer. + # The table is the ``fitting_routes`` argument of the schema; a call + # that leaves it to its default of no table records none. schema = torch.ops.deepmd.dpa4c_canonical_compress_energy_force.default._schema + position = [argument.name for argument in schema.arguments].index( + "fitting_routes" + ) literals = [ - node.args[-1] if len(node.args) == len(schema.arguments) else None + node.args[position] + if len(node.args) > position + else node.kwargs.get("fitting_routes") for node in exported.graph_module.graph.nodes if "dpa4c_canonical_compress_energy_force" in str(node.target) ] @@ -4780,6 +4794,60 @@ def test_two_routes_besides_the_rules_are_decided_on_trains( ) +@_GPU +def test_the_route_tuner_times_the_first_block_of_several() -> None: + """The tuner times the routes of a model of two blocks on the operator of its first block. + + The routes of a network change no further message-passing block, so the + bench evaluates a copy of the descriptor without its further blocks, whose + operator it captures, and the descriptor of the model keeps its blocks. + """ + from deepmd.pt_expt.kernels import ( + fitting_routes, + ) + from deepmd.pt_expt.model.get_model import ( + get_model, + ) + + model = ( + get_model( + { + "type_map": ["O", "H"], + "descriptor": { + "type": "dpa4c", + "rcut": [4.0, 3.0], + "n_blocks": 2, + "channels": 8, + "lmax": 2, + "n_radial": 8, + "precision": "float32", + "seed": 3, + }, + "fitting_net": { + "type": "ener", + "neuron": [64, 64], + "activation_function": "silu", + "precision": "float32", + "resnet_dt": False, + "seed": 3, + }, + } + ) + .to("cpu") + .eval() + ) + model.get_descriptor().enable_compression(min_nbor_dist=0.5) + device = torch.device("cuda", torch.cuda.current_device()) + fitting = model.atomic_model.fused_decomposition()[0].fitting_net + bench = fitting_routes._Bench( + model, device, 512, fitting, fitting.bias_atom_e[:, 0] + ) + assert not bench.descriptor.has_message_passing() + assert model.get_descriptor().has_message_passing() + graphs = bench._capture(bench._inputs(512), [fitting_routes.RULES], 0) + assert list(graphs) == [fitting_routes.RULES] + + @_GPU def test_the_route_tuner_measures_a_table_that_changes_no_output( monkeypatch: pytest.MonkeyPatch, @@ -4839,3 +4907,571 @@ def test_the_route_tuner_measures_a_table_that_changes_no_output( ) for expected, actual in zip(rules, routed, strict=True): assert torch.equal(expected, actual), node_count + + +# === Descriptors of several message-passing blocks === +# +# The further blocks run in the canonical fused operator. Their output maps +# start at zero, which makes a fresh block the identity, so every comparison +# below draws those maps at random first (`_activate_blocks`). + + +def _activate_blocks(descriptor: DescrptDPA4C) -> None: + """Draw every zero-initialized map and the field gains of the further blocks.""" + generator = np.random.default_rng(97) + with torch.no_grad(): + for block in descriptor.attentions: + for module in block.modules(): + weight = getattr(module, "w", None) + if ( + isinstance(weight, torch.Tensor) + and weight.ndim == 2 + and not weight.any() + ): + weight.copy_( + torch.as_tensor( + generator.normal(size=tuple(weight.shape)), + dtype=weight.dtype, + ) + ) + gain = block.adam_field_gain + gain.copy_( + torch.as_tensor( + generator.normal(size=tuple(gain.shape)), dtype=gain.dtype + ) + ) + + +def _build_block_descriptor( + channels: int, + lmax: int, + radial_modes: int, + rcut: Sequence[float], + spin: bool = False, + **window: float, +) -> DescrptDPA4C: + """Return an fp32 descriptor of ``len(rcut)`` blocks with active further blocks. + + Block ``k`` reads the edges within ``rcut[k]``. A spin-conditioned + descriptor is prepared as in `_build_spin_descriptor`, and ``window`` + holds the fractions of a bridging window. The descriptor is not + compressed. + """ + builder = _build_spin_descriptor if spin else _build_descriptor + descriptor = builder( + channels, lmax, radial_modes, rcut=list(rcut), n_blocks=len(rcut), **window + ) + _activate_blocks(descriptor) + return descriptor + + +#: Side in Å of the random clusters of a descriptor of several blocks with a +#: bridging window. Nearly every atom of a denser cluster holds a pair inside +#: the window, so that the source gates mute most of the messages of its +#: further blocks; in this one they change the energy by a few thousandths. +_WINDOWED_SIDE = 6.0 + + +def _canonical_cluster( + descriptor: DescrptDPA4C, node_count: int = 40, side: float = 5.0 +) -> tuple[Any, Any, torch.Tensor]: + """Return the neighbor graph, the compact canonical graph and the types of a cluster.""" + from deepmd.pt_expt.utils.canonical_graph import ( + canonical_graph_from_neighbor_graph, + ) + + neighbor_graph, atype = _build_graph( + descriptor, canonical=True, node_count=node_count, side=side + ) + graph = canonical_graph_from_neighbor_graph( + dataclasses.replace(neighbor_graph, n_local=neighbor_graph.n_node) + ) + return neighbor_graph, graph, atype + + +@_GPU +@pytest.mark.parametrize( + ("channels", "lmax", "radial_modes", "rcut"), + [ + (8, 2, 0, (3.0, 3.0)), + (32, 2, 0, (3.0, 2.5)), + (64, 2, 0, (3.0, 3.0)), + (64, 3, 4, (3.0, 2.5)), + (128, 3, 4, (3.0, 2.5)), + (16, 4, 2, (3.0, 2.5, 2.0)), + ], +) +@pytest.mark.parametrize("windowed", [False, True]) +def test_further_blocks_match_the_uncompressed_model( + channels: int, + lmax: int, + radial_modes: int, + rcut: tuple[float, ...], + windowed: bool, +) -> None: + """The fused operator of several blocks reproduces the uncompressed model. + + The energy, the forces, the virial and the per-atom virial of the + compressed descriptor and the fused fitting are compared with those of the + uncompressed descriptor and fitting differentiated by autograd. The record + of every further block is packed from the trained maps, so the comparison + covers the packing as well as the kernels; and the further blocks must + change the energy by a hundred times the tolerance, which a descriptor of + fresh blocks would not. A bridging window mutes every edge that an atom of + its frozen zone emits towards a third atom through the source gate, whose + slope through the switches of the pairs of a node belongs to that node; + the per-atom virial, which the model attributes to the source of every + edge, pins that attribution. The cluster holds pairs in the frozen zone, + in the window and beyond it. + """ + from deepmd.pt_expt.kernels.dpa4c import ( + canonical, + ) + from deepmd.pt_expt.kernels.edge_force_virial import ( + edge_force_virial, + ) + + window = _WINDOW if windowed else {} + descriptor = _build_block_descriptor(channels, lmax, radial_modes, rcut, **window) + neighbor_graph, graph, atype = _canonical_cluster( + descriptor, side=_WINDOWED_SIDE if windowed else 5.0 + ) + if windowed: + reduced = _reduced_distance(descriptor, neighbor_graph, atype) + inner, outer = window.values() + assert (reduced < inner).sum() > 8 and (reduced > outer).any() + assert ((reduced > inner) & (reduced < outer)).sum() > 8 + fitting = _energy_fitting(descriptor) + + def uncompressed(model: DescrptDPA4C) -> tuple[torch.Tensor, ...]: + edge_vec = neighbor_graph.edge_vec.detach().clone().requires_grad_(True) + node_descriptor, _ = model.call_graph( + dataclasses.replace(neighbor_graph, edge_vec=edge_vec), + atype, + type_embedding=model.type_embedding.call(), + ) + atom_energy = fitting.call_graph(node_descriptor, atype)[fitting.var_name] + (edge_gradient,) = torch.autograd.grad(atom_energy.sum(), edge_vec) + force, atom_virial, virial, _ = edge_force_virial( + edge_gradient, + edge_vec.detach(), + neighbor_graph.edge_index, + neighbor_graph.edge_mask, + neighbor_graph.destination_order, + neighbor_graph.destination_row_ptr, + neighbor_graph.source_order, + neighbor_graph.source_row_ptr, + neighbor_graph.n_node, + edge_vec.new_empty(0), + atype.shape[0], + True, + ) + return atom_energy.detach().sum().double(), force, virial, atom_virial + + energy, force, virial, atom_virial = uncompressed(descriptor) + # Fresh further blocks are the identity, so this descriptor evaluates the + # first block alone. + first_block = _build_descriptor( + channels, lmax, radial_modes, rcut=list(rcut), n_blocks=len(rcut), **window + ) + first_energy = uncompressed(first_block)[0] + descriptor._set_compression(build_compression_artifacts(descriptor)) + fused = canonical.dpa4c_canonical_compress_energy_force( + descriptor, fitting, graph, atype, fitting.bias_atom_e[:, 0] + ) + energy_tolerance = 1e-5 * max(energy.abs().item(), 1.0) + force_scale = max(force.abs().max().item(), 1.0) + assert (energy - first_energy).abs().item() > 100 * energy_tolerance + torch.testing.assert_close( + fused[0].reshape(()), energy, atol=energy_tolerance, rtol=0 + ) + torch.testing.assert_close( + fused[2].reshape(-1, 3).float(), + force, + atol=2e-4 * force_scale, + rtol=0, + ) + torch.testing.assert_close( + fused[3].reshape(3, 3).float(), + virial.reshape(3, 3), + atol=2e-4 * max(virial.abs().max().item(), 1.0), + rtol=0, + ) + torch.testing.assert_close( + fused[4].float(), + atom_virial, + atol=2e-4 * max(atom_virial.abs().max().item(), 1.0), + rtol=0, + ) + + +@_GPU +@pytest.mark.parametrize(("channels", "lmax", "radial_modes"), [(32, 2, 0), (64, 3, 4)]) +def test_further_block_scans_take_their_rows_from_the_graph( + channels: int, lmax: int, radial_modes: int +) -> None: + """Guard slots of the edge storage leave every output of a model of two blocks unchanged. + + A block of an edge scan of a further block takes its number of rows from + the edges of the graph of the block, which set how full its panels are, + and the summation order of every row follows from that number. The grid of + the launch provides for the rows that the edge storage implies, which holds + at least as many slots; guard slots past the graph can make it provide for + fewer rows per block, and so for more blocks, which retire past the rows of + the scan. Clusters of 500 to 1,500 atoms, whose blocks fill a wave of the + device or a few, take their rows from the fill of their panels; each + evaluates on its own edge storage and on one of ten times as many slots, + and every output of the two agrees bit for bit. + """ + from deepmd.pt_expt.kernels.dpa4c.canonical import ( + dpa4c_canonical_compress_energy_force, + ) + + descriptor = _build_block_descriptor(channels, lmax, radial_modes, (3.0, 2.5)) + descriptor._set_compression(build_compression_artifacts(descriptor)) + fitting = _energy_fitting(descriptor) + for node_count in (500, 1000, 1500): + _, graph, atype = _canonical_cluster( + descriptor, + node_count=node_count, + side=5.0 * (node_count / 40) ** (1.0 / 3.0), + ) + storage = graph.source.shape[0] + outputs = [ + dpa4c_canonical_compress_energy_force( + descriptor, fitting, edges, atype, fitting.bias_atom_e[:, 0] + ) + for edges in (graph, _padded_storage(graph, 9 * storage)) + ] + for index, (compact, padded) in enumerate(zip(*outputs, strict=True)): + assert torch.equal(compact, padded), (node_count, index) + + +@_GPU +@pytest.mark.parametrize(("channels", "lmax", "radial_modes"), [(32, 2, 0), (64, 3, 4)]) +def test_further_block_scans_tile_like_the_whole_system( + channels: int, lmax: int, radial_modes: int, monkeypatch: pytest.MonkeyPatch +) -> None: + """Node tiles of a multiple of four rows change no output of a model of two blocks. + + Every run of a tiled system takes the rows per block that the edges of the + whole system set, and a run that starts at a multiple of four rows groups + its rows into blocks as the whole system does, so the panels of every + block, and the summation order of every row, stay those of the untiled + system. A cluster of 1,000 atoms, whose scans take two or four rows per + block, evaluates untiled and in runs of 16, 256 and 600 rows, which start + past the first row of the graph, and every output agrees bit for bit. + """ + from deepmd.pt_expt.kernels.dpa4c.canonical import ( + dpa4c_canonical_compress_energy_force, + ) + + descriptor = _build_block_descriptor(channels, lmax, radial_modes, (3.0, 2.5)) + descriptor._set_compression(build_compression_artifacts(descriptor)) + fitting = _energy_fitting(descriptor) + node_count = 1000 + _, graph, atype = _canonical_cluster( + descriptor, + node_count=node_count, + side=5.0 * (node_count / 40) ** (1.0 / 3.0), + ) + + def run() -> tuple[torch.Tensor, ...]: + return dpa4c_canonical_compress_energy_force( + descriptor, fitting, graph, atype, fitting.bias_atom_e[:, 0] + ) + + monkeypatch.setenv("DP_NODE_TILE", "0") + reference = run() + for tile in (16, 256, 600): + monkeypatch.setenv("DP_NODE_TILE", str(tile)) + for index, (actual, expected) in enumerate(zip(run(), reference, strict=True)): + assert torch.equal(actual, expected), (tile, index) + + +@_GPU +@pytest.mark.parametrize( + ("channels", "lmax", "radial_modes", "rcut", "spin", "windowed"), + [ + (8, 2, 0, (3.0, 3.0), False, False), + (16, 3, 4, (3.0, 2.5), False, False), + (32, 2, 0, (3.0, 2.5), False, False), + (64, 2, 0, (3.0, 3.0), False, False), + (64, 3, 4, (3.0, 2.5), False, False), + (128, 3, 4, (3.0, 2.5), False, False), + (16, 4, 2, (3.0, 2.5, 2.0), False, False), + (32, 2, 0, (3.0, 2.6), True, False), + (8, 2, 0, (3.0, 3.0), False, True), + (64, 3, 4, (3.0, 2.5), False, True), + (16, 4, 2, (3.0, 2.5, 2.0), False, True), + (32, 2, 0, (3.0, 2.6), True, True), + ], +) +def test_further_blocks_match_the_reference( + channels: int, + lmax: int, + radial_modes: int, + rcut: tuple[float, ...], + spin: bool, + windowed: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The CUDA scans of the further blocks follow the CPU reference. + + The profiles cover every panel geometry of the further-block scans and a + descriptor of three blocks with decreasing cutoffs; a spin-conditioned + descriptor carries the magnetic force of its first block through the + further ones. A bridging window adds the source gate of every edge and + the slope of the switches through it, with and without the pair potential + of the window. + """ + descriptor = _build_block_descriptor( + channels, lmax, radial_modes, rcut, spin, **(_WINDOW if windowed else {}) + ) + descriptor._set_compression(build_compression_artifacts(descriptor)) + _check_canonical_against_reference( + descriptor, + windowed, + monkeypatch, + single_type=False, + side=_WINDOWED_SIDE if windowed else 5.0, + ) + + +def _fold_halo(outputs: Sequence[torch.Tensor], owner: torch.Tensor, owned: int): + """Fold the forces and per-atom virials of halo rows onto their owners.""" + energy, atom_energy, force, virial, atom_virial, force_mag, mask = outputs + index = owner.to(force.device) + folded_force = force.new_zeros(owned, 3).index_add_(0, index, force) + folded_virial = atom_virial.new_zeros(owned, 3, 3).index_add_(0, index, atom_virial) + folded_mag = force_mag + if force_mag.numel(): + folded_mag = force_mag.new_zeros(owned, 3).index_add_(0, index, force_mag) + return ( + energy, + atom_energy[:owned], + folded_force, + virial, + folded_virial, + folded_mag, + mask[:owned], + ) + + +def _assert_outputs_close( + actual: Sequence[torch.Tensor], expected: Sequence[torch.Tensor] +) -> None: + """Compare operator outputs at the tolerance of the canonical parity tests.""" + for value, reference in zip(actual, expected, strict=True): + reference = reference.cpu() + scale = max(reference.abs().max().item(), 1.0) if reference.numel() else 1.0 + torch.testing.assert_close( + value.cpu().to(reference.dtype), reference, atol=2e-5 * scale, rtol=2e-5 + ) + + +def _frame_graph( + points: torch.Tensor, + owned: int, + rcut: float, + owner: torch.Tensor | None = None, +) -> Any: + """Return the compact canonical graph of the rows of the first ``owned`` atoms. + + Every atom within ``rcut`` of an owned atom is the source of one of its + edges. The node set holds every atom, the rows of the others without + edges, or, given the ``owner`` of every atom, the owned atoms alone, every + edge then leading from the owner of its source. + """ + from deepmd.pt_expt.utils.canonical_graph import ( + canonical_graph_from_neighbor_graph, + ) + + distance = torch.cdist( + points[:owned], points, compute_mode="donot_use_mm_for_euclid_dist" + ) + destination, source = torch.nonzero( + (distance < rcut) & (distance > 1e-8), as_tuple=True + ) + edge_vec = (points[source] - points[destination]).to(torch.float32) + node_count = points.shape[0] + if owner is not None: + source = owner[source] + node_count = owned + graph = NeighborGraph( + n_node=torch.tensor([node_count], device=points.device), + edge_index=torch.stack((source, destination)), + edge_vec=edge_vec, + edge_mask=torch.ones(source.shape[0], dtype=torch.bool, device=points.device), + n_local=torch.tensor([owned], device=points.device), + ) + return canonical_graph_from_neighbor_graph( + attach_edge_csr(graph, node_count, canonicalize=True) + ) + + +def _border_images( + points: np.ndarray, side: float, cut: float +) -> tuple[np.ndarray, np.ndarray, list[list[int]], list[int]]: + """Emulate the border swaps of one process of a LAMMPS brick decomposition. + + Every dimension takes two swaps, as in LAMMPS: the atoms within ``cut`` of + the lower face travel as images beyond the upper face, then those within + ``cut`` of the upper face as images below the lower face. Both swaps of a + dimension choose among the atoms present before its first swap, owned or + received in an earlier dimension. Returns the coordinates of every atom, + owned first, the owner of every atom, the swap table and the send list. + """ + images = list(points) + owner = list(range(len(points))) + swaps = [] + send = [] + for dimension in range(3): + present = len(images) + for shift in (side, -side): + chosen = [ + i + for i in range(present) + if ( + images[i][dimension] < cut + if shift > 0 + else images[i][dimension] >= side - cut + ) + ] + first = len(images) + for i in chosen: + image = images[i].copy() + image[dimension] += shift + images.append(image) + owner.append(owner[i]) + swaps.append([0, 0, len(chosen), len(chosen), first]) + send.extend(chosen) + return np.array(images), np.array(owner), swaps, send + + +@_GPU +@pytest.mark.parametrize( + ("channels", "lmax", "radial_modes", "rcut", "spin"), + [ + (32, 2, 0, (3.0, 3.0), False), + (64, 3, 4, (3.0, 2.5), False), + (32, 2, 0, (3.0, 2.6), True), + ], +) +@pytest.mark.parametrize("swaps", ["self", "lammps", "lammps-crossing"]) +@pytest.mark.parametrize("windowed", [False, True]) +def test_halo_rows_match_the_folded_frame( + channels: int, + lmax: int, + radial_modes: int, + rcut: tuple[float, ...], + spin: bool, + swaps: str, + windowed: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A node set with halo rows and its border plan matches the folded frame. + + The owned atoms of a periodic frame keep complete rows, and every periodic + image within reach becomes a halo row without edges, which the border plan + refreshes from its owner before every further block: by one self swap of + all images, or by the six swaps of one process of a LAMMPS brick + decomposition, whose later swaps forward images received by earlier ones. + The forces of the halo rows, folded onto their owners, and every other + output match those of the folded frame, in which every edge leads from the + owner itself, on the device and in the CPU reference. Under a bridging + window the border plan also carries the switch totals of the source gate + to the halo rows, and returns to their owners the gate cotangents that + the halo rows gather as sources of edges; pairs of the frozen zone and of + the window cross the faces of the frame. + + A plan that names a communicator crosses processes, and the operator then + scans the rows whose edges read no halo row while it exchanges the halo + rows, and the other rows after the exchange. An operator library without + MPI copies the rows of the self swaps of such a plan on the device, which + the crossing case takes; the CPU reference serves single-process plans + alone. + """ + from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, + ) + + crossing = swaps == "lammps-crossing" + if crossing and bool(torch.ops.deepmd.enable_mpi()): + pytest.skip("an operator library with MPI reads the communicator") + owned, side = 48, 7.0 + descriptor = _build_block_descriptor( + channels, lmax, radial_modes, rcut, spin, **(_WINDOW if windowed else {}) + ) + descriptor._set_compression(build_compression_artifacts(descriptor)) + fitting = _energy_fitting(descriptor) + generator = torch.Generator(device="cuda").manual_seed(41) + local = side * torch.rand( + owned, 3, dtype=torch.float64, device="cuda", generator=generator + ) + local_type = torch.arange(owned, device="cuda") % 2 + cut = max(rcut) + if swaps == "self": + shifts = torch.cartesian_prod(*[torch.tensor([-1.0, 0.0, 1.0])] * 3) + shifts = side * shifts[shifts.abs().sum(-1) > 0].to(local) + images = (local[None] + shifts[:, None]).reshape(-1, 3) + near = ( + torch.cdist(images, local, compute_mode="donot_use_mm_for_euclid_dist") + .amin(-1) + .lt(cut) + ) + points = torch.cat((local, images[near])) + local_index = torch.arange(owned, device="cuda") + owner = torch.cat((local_index, local_index.repeat(shifts.shape[0])[near])) + halo = points.shape[0] - owned + plan = BorderPlan( + send_nodes=owner[owned:].to(torch.int32).contiguous(), + swaps=torch.tensor([[0, 0, halo, halo, owned]], dtype=torch.int32), + communicator=torch.zeros(1, dtype=torch.int64), + ) + else: + images, owner_array, table, send = _border_images( + local.cpu().numpy(), side, cut + 0.5 + ) + points = torch.as_tensor(images, device="cuda") + owner = torch.as_tensor(owner_array, device="cuda") + # A placeholder address names a communicator, which an operator + # library without MPI never reads. + plan = BorderPlan( + send_nodes=torch.tensor(send, dtype=torch.int32, device="cuda"), + swaps=torch.tensor(table, dtype=torch.int32), + communicator=torch.full((1,), int(crossing), dtype=torch.int64), + ) + assert points.shape[0] > owned + moment = halo_moment = None + if spin: + moment = torch.randn(owned, 3, device="cuda", generator=generator) + halo_moment = moment[owner] + operator = torch.ops.deepmd.dpa4c_canonical_compress_energy_force + reference = operator( + *_fused_arguments( + monkeypatch, + descriptor, + fitting, + _frame_graph(points, owned, cut, owner), + local_type, + fitting.bias_atom_e[:, 0], + moment, + ) + ) + arguments = _fused_arguments( + monkeypatch, + descriptor, + fitting, + _frame_graph(points, owned, cut), + local_type[owner], + fitting.bias_atom_e[:, 0], + halo_moment, + border=plan, + ) + _assert_outputs_close(_fold_halo(operator(*arguments), owner, owned), reference) + if not crossing: + _assert_outputs_close( + _fold_halo(operator(*[_to_cpu(a) for a in arguments]), owner, owned), + reference, + ) diff --git a/source/tests/pt_expt/infer/test_deep_eval.py b/source/tests/pt_expt/infer/test_deep_eval.py index 112efd99ab..088114355a 100644 --- a/source/tests/pt_expt/infer/test_deep_eval.py +++ b/source/tests/pt_expt/infer/test_deep_eval.py @@ -2565,18 +2565,43 @@ def test_a_state_served_later_answers_as_one_served_first(self) -> None: np.testing.assert_allclose(value, reference, rtol=1e-6, atol=1e-6) +class TestGraphInputLayout(unittest.TestCase): + """A graph archive answers for broadcast inputs as for contiguous ones.""" + + def test_broadcast_frames_match_their_copies(self) -> None: + """Frames given as zero-stride views evaluate like their copies. + + A batch of identical cells is naturally a broadcast view, whose zero + frame stride survives the conversion to a tensor. + """ + model = _charge_state_model(resnet_dt=True) + rng = np.random.default_rng(GLOBAL_SEED) + nframes = 3 + coords = np.broadcast_to(rng.random((1, 5, 3)) * 6.0, (nframes, 5, 3)) + cells = np.broadcast_to(np.eye(3).reshape(1, 9) * 12.0, (nframes, 9)) + atom_types = np.array([0, 1, 0, 1, 0], dtype=np.int32) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "model.pt2") + deserialize_to_file( + path, {"model": model.serialize()}, lower_kind="graph", with_comm=False + ) + dp = DeepPot(path) + actual = dp.eval(coords, cells, atom_types) + expected = dp.eval(coords.copy(), cells.copy(), atom_types) + for value, reference in zip(actual, expected, strict=True): + np.testing.assert_allclose(value, reference, rtol=1e-6, atol=1e-6) + + @unittest.skipUnless( - torch.cuda.is_available() and dpa4c_op_available(), - "CUDA and the compiled DPA4C operator are required", + dpa4c_op_available(), + "the compiled DPA4C operator of the backend device is required", ) class TestCompressedChargeStateRoutes(unittest.TestCase): """A compressed archive must serve one charge state to all of its routes. - Compression folds the condition into frozen tables that only the fused - kernel behind the compiled lower reads, while ``eval_descriptor`` and - ``eval_fitting_last_layer`` evaluate the model deserialized beside that - lower, which reads the condition as an argument. Both routes have to - answer for the state the caller asked for. + Compression folds the condition into frozen tables. The compiled lower + and the model deserialized beside it must both receive the requested + state, including descriptor and fitting-layer introspection. """ lower_kind = "graph" @@ -2592,6 +2617,7 @@ def setUpClass(cls) -> None: cls.tmpfile = tempfile.NamedTemporaryFile(suffix=".pt2", delete=False) cls.tmpfile.close() + previous_device = torch.get_default_device() torch.set_default_device(None) try: deserialize_to_file( @@ -2605,7 +2631,7 @@ def setUpClass(cls) -> None: cls.dp = DeepPot(cls.tmpfile.name) assert cls.dp.deep_eval.metadata["lower_input_kind"] == cls.lower_kind finally: - torch.set_default_device("cuda:9999999") + torch.set_default_device(previous_device) rng = np.random.default_rng(GLOBAL_SEED) natoms = 5 @@ -2663,6 +2689,10 @@ def test_a_state_is_not_left_behind(self) -> None: np.testing.assert_allclose(self._routes([0.0, 1.0]), first, rtol=1e-6) +@unittest.skipUnless( + DEVICE.type == "cuda" and dpa4c_op_available(), + "CUDA and the compiled DPA4C operator are required", +) class TestCanonicalChargeStateRoutes(TestCompressedChargeStateRoutes): """Canonical archives retain charge folding and both graph input paths.""" diff --git a/source/tests/pt_expt/infer/test_embedding.py b/source/tests/pt_expt/infer/test_embedding.py index f443acd708..c04702eccd 100644 --- a/source/tests/pt_expt/infer/test_embedding.py +++ b/source/tests/pt_expt/infer/test_embedding.py @@ -32,6 +32,9 @@ ) from deepmd.pt.model.model import get_model as pt_get_model from deepmd.pt.train.wrapper import ModelWrapper as PtModelWrapper +from deepmd.pt.utils.auto_batch_size import ( + AutoBatchSize, +) from deepmd.pt_expt.kernels.dpa4c import ( graph_compress, ) @@ -664,20 +667,47 @@ def test_compressed_charge_state( ) _assert_embeddings_close(actual, expected[name], rtol=1e-4, atol=1e-5) assert kernel.call_count == len(states) - # The folded tables hold one state, which all frames of a call share. - with pytest.raises(ValueError, match="single state"): - frozen.eval_embedding( - np.tile(_COORDS[:1], (2, 1, 1)), - np.tile(_CELLS[:1], (2, 1)), - atype, - charge_spin=np.concatenate(list(states.values())), - ) + # The whole call shares one folded state even when batching splits frames. + for batch_size in (None, AutoBatchSize(initial_batch_size=len(atype))): + monkeypatch.setattr(frozen.deep_eval, "auto_batch_size", batch_size) + with pytest.raises(ValueError, match="single state"): + frozen.eval_embedding( + np.tile(_COORDS[:1], (2, 1, 1)), + np.tile(_CELLS[:1], (2, 1)), + atype, + charge_spin=np.concatenate(list(states.values())), + ) assert ( np.abs(expected["other"][1] - expected["default"][1]).max() > 1e-2 * np.abs(expected["default"][1]).max() ) +def test_multiblock_canonical_metadata_keeps_the_embedding_graph_generic( + tmp_path: "os.PathLike[str]", +) -> None: + """The archive's energy ABI does not change the embedding graph layout.""" + config = copy.deepcopy(_DPA4C_CONFIG) + config["descriptor"].update(n_blocks=2, precision="float32") + config["fitting_net"]["precision"] = "float32" + model_params = _normalize_model(config) + model = get_model(copy.deepcopy(model_params)).eval() + _perturb(model, seed=5) + dp = DeepPot( + _save_checkpoint(model, model_params, os.path.join(tmp_path, "model.pt")) + ) + dp.deep_eval._dpmodel.get_descriptor().enable_compression(0.5) + expected = dp.eval_embedding(_COORDS[:1], _CELLS[:1], _ATYPES[0]) + # Canonical archive metadata is sufficient to exercise the CPU embedding + # path: no compiled energy/force entry point is called by this API. + dp.deep_eval.metadata.update( + lower_input_kind="dpa4c_canonical", has_message_passing=True + ) + actual = dp.eval_embedding(_COORDS[:1], _CELLS[:1], _ATYPES[0]) + # The fp32 graph reductions need not be bitwise repeatable on CUDA. + _assert_embeddings_close(actual, expected, rtol=1e-6, atol=1e-6) + + def test_rejects_a_model_without_graph_forward(tmp_path: "os.PathLike[str]") -> None: """A model that is not evaluated on the neighbor graph has no embedding.""" model_params = _normalize_model( diff --git a/source/tests/pt_expt/model/test_dpa4c_graph_lower.py b/source/tests/pt_expt/model/test_dpa4c_graph_lower.py index ba377697db..4a4365e625 100644 --- a/source/tests/pt_expt/model/test_dpa4c_graph_lower.py +++ b/source/tests/pt_expt/model/test_dpa4c_graph_lower.py @@ -1,5 +1,6 @@ # SPDX-License-Identifier: LGPL-3.0-or-later +import re from types import ( SimpleNamespace, ) @@ -8,6 +9,7 @@ import pytest import torch +from deepmd.pt_expt.kernels.dpa4c import canonical as dpa4c_canonical from deepmd.pt_expt.model.get_model import ( get_model, ) @@ -21,6 +23,7 @@ _resolve_lower_kind, _trace_and_export, build_synthetic_graph_inputs, + compressed_export_unsupported_reason, ) #: The compact canonical ABI and the fused spin backward are CUDA-only routes, @@ -71,6 +74,35 @@ def _compressed_config(channels: int = 8) -> dict: return config +def test_multiblock_communication_is_specific_to_the_lower() -> None: + """Canonical halo exchange belongs to its main ABI, not a sibling archive.""" + from deepmd.pt_expt.utils.serialization import ( + _collect_metadata, + _needs_with_comm_artifact, + ) + + config = _compressed_config() + config["descriptor"]["n_blocks"] = 2 + model = get_model(config) + assert model.atomic_model.has_message_passing_across_ranks() + for kind, needs_sibling in ( + ("graph", True), + ("nlist", False), + ("dpa4c_canonical", False), + ): + assert _needs_with_comm_artifact(model, kind) is needs_sibling + metadata = _collect_metadata(model, lower_kind=kind) + assert metadata["has_message_passing"] is True + assert metadata["has_comm_artifact"] is needs_sibling + if not needs_sibling: + with pytest.raises(ValueError, match=r"with_comm_dict.*lower"): + _trace_and_export( + {"model": model.serialize()}, + lower_kind=kind, + with_comm_dict=True, + ) + + def _run_graph( model: torch.nn.Module, dtype: torch.dtype = torch.float64, @@ -671,6 +703,121 @@ def test_compact_canonical_export_accepts_source_csr_placeholders( assert torch.equal(declined[key], value), key +@_GPU +def test_a_multi_block_export_reads_its_border_plan( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The compact lower of further message-passing blocks reads its border plan. + + The communicator and the border plan follow the graph by name, since their + positions are those of the long-range inputs of the energy lower; a program + that took them for long-range inputs would ignore the halo rows of a + decomposed frame and give wrong energies on several ranks. Each of them + must reach the fused operator, and the metadata must announce the message + passing, from which the C++ interface decides to pass a border plan. + """ + monkeypatch.setenv("DP_CUDA_INFER", "2") + config = _compressed_config(8) + config["descriptor"]["n_blocks"] = 2 + model = get_model(config).to("cpu").eval() + model.get_descriptor().enable_compression(min_nbor_dist=0.5) + exported, metadata, _model_json, _output_keys = _trace_and_export( + {"model": model.serialize()}, + lower_kind="dpa4c_canonical", + do_atomic_virial=True, + ) + assert metadata["has_message_passing"] + user_inputs = exported.graph_signature.user_inputs + placeholders = { + node.name: node + for node in exported.graph_module.graph.nodes + if node.op == "placeholder" + } + for name, expected in zip( + user_inputs[-3:], ("communicator", "halo_send", "halo_swaps"), strict=True + ): + assert name.startswith(expected), user_inputs + assert any( + user.target + is torch.ops.deepmd.dpa4c_canonical_compress_energy_force.default + for user in placeholders[name].users + ), name + + +@pytest.mark.parametrize( + ("change", "condition"), + [ + ({"pair_exclude_types": [[0, 1]]}, "pair_exclude_types"), + ({"fitting_net": {"resnet_dt": True}}, "energy fitting"), + ], +) +def test_a_multi_block_model_the_canonical_operators_cannot_serve_is_refused( + monkeypatch: pytest.MonkeyPatch, change: dict, condition: str +) -> None: + """A compressed model of several blocks is refused rather than evaluated uncompressed. + + The operators of a generic lower evaluate one block, so a compressed model + of several blocks that the compact canonical operators of a CUDA target do + not serve, here one that excludes a type pair or whose energy fitting + takes a timestep per layer, would evaluate its descriptor through the + uncompressed equations there. The automatic selection of the lower + reports the failing condition instead, and a freeze learns it from the + uncompressed model. The judgment reads the configuration alone, so the + test targets CUDA on any device. + """ + monkeypatch.setattr(dpa4c_canonical, "backend_device_type", lambda: "cuda") + config = _compressed_config(8) + config["descriptor"]["n_blocks"] = 2 + for key, value in change.items(): + if isinstance(value, dict): + config[key].update(value) + else: + config[key] = value + model = get_model(config).to("cpu").eval() + pattern = f"compact canonical.*{condition}" + assert re.search(pattern, compressed_export_unsupported_reason(model) or "") + model.get_descriptor().enable_compression(min_nbor_dist=0.5) + with pytest.raises(ValueError, match=pattern): + _resolve_lower_kind("model.pt2", {"model": model.serialize()}, "auto") + + +def test_compression_preflight_checks_canonical_operator_availability( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(dpa4c_canonical, "backend_device_type", lambda: "cuda") + monkeypatch.setattr(dpa4c_canonical, "op_available", lambda: False) + config = _compressed_config(8) + config["descriptor"]["n_blocks"] = 2 + model = get_model(config).to("cpu").eval() + assert ( + "lacks the compact canonical operators" + in compressed_export_unsupported_reason(model) + ) + model.get_descriptor().enable_compression(0.5) + assert dpa4c_canonical.canonical_model_eligible(model) + + +def test_a_freeze_judges_a_case_embedding_as_the_export_folds_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A model of several blocks with a case embedding deploys compressed. + + The export folds the case embedding of a deployed branch into the first + layer of its fitting, which the fused fitting kernels then reproduce, so + the judgment of a freeze before compression folds it too, on a copy that + leaves the model unchanged. + """ + monkeypatch.setattr(dpa4c_canonical, "backend_device_type", lambda: "cuda") + monkeypatch.setattr(dpa4c_canonical, "op_available", lambda: True) + config = _compressed_config(8) + config["descriptor"]["n_blocks"] = 2 + config["fitting_net"]["dim_case_embd"] = 2 + model = get_model(config).to("cpu").eval() + model.set_case_embd(1) + assert compressed_export_unsupported_reason(model) is None + assert model.get_fitting_net().dim_case_embd == 2 + + @_GPU @pytest.mark.parametrize("index_dtype", [torch.uint32, torch.int64]) def test_canonical_atom_virial_sums_to_frame( diff --git a/source/tests/pt_expt/model/test_dpa4c_parallel.py b/source/tests/pt_expt/model/test_dpa4c_parallel.py new file mode 100644 index 0000000000..322f8c3365 --- /dev/null +++ b/source/tests/pt_expt/model/test_dpa4c_parallel.py @@ -0,0 +1,240 @@ +# SPDX-License-Identifier: LGPL-3.0-or-later +"""Cross-rank ghost exchange of a multi-block DPA4C, on one rank. + +Reference = the folded periodic graph, whose edge sources are the owners, so +every source feature is complete by construction. Candidate = the unfolded +LAMMPS layout, owners followed by ghost images with edges for owned +destinations only, completed by a self-send ``border_op`` swap that maps every +ghost slot to its owner. The ghost rows receive no edges, so without the +exchange the second block would read zero moments for every neighbor across +the cell boundary. +""" + +import copy +import ctypes + +import numpy as np +import pytest +import torch + +from deepmd.dpmodel.utils.neighbor_graph import ( + build_neighbor_graph, +) +from deepmd.dpmodel.utils.nlist import ( + build_neighbor_list, + extend_coord_with_ghosts, +) +from deepmd.pt_expt.model.get_model import ( + get_model, +) +from deepmd.pt_expt.utils.comm import ( + ensure_comm_registered, +) + +RCUT = 4.0 +BOX = 6.0 +ATYPE = np.array([[0, 0, 1, 1, 0]], dtype=np.int64) +COORD = np.array( + [ + [ + [0.3, 3.0, 3.0], + [5.4, 3.1, 2.8], + [2.5, 3.0, 3.2], + [3.6, 4.2, 3.0], + [1.4, 1.1, 4.7], + ] + ], + dtype=np.float64, +) +CONFIG = { + "type_map": ["O", "H"], + "descriptor": { + "type": "dpa4c", + "rcut": [RCUT, 3.5], + "n_blocks": 2, + "channels": 16, + "lmax": 3, + "n_radial": 8, + "radial_modes": 2, + "precision": "float64", + "seed": 7, + }, + "fitting_net": {"neuron": [16, 16], "precision": "float64", "seed": 7}, +} +ZBL_CONFIG = { + **CONFIG, + "type_map": ["O", "He"], + "bridging_method": "zbl", + "bridging_r_inner": 0.8, + "bridging_r_outer": 1.2, +} +THREE_BLOCK_CONFIG = { + **ZBL_CONFIG, + "descriptor": {**CONFIG["descriptor"], "rcut": [RCUT, 3.5, 3.5], "n_blocks": 3}, +} + + +def _perturb(model: torch.nn.Module) -> torch.nn.Module: + """Move every weight off its initialization, the zero maps included.""" + generator = torch.Generator(device="cpu").manual_seed(11) + with torch.no_grad(): + for parameter in model.parameters(): + if parameter.is_floating_point(): + noise = torch.randn( + parameter.shape, generator=generator, dtype=parameter.dtype + ) + parameter.add_(0.3 * noise.to(parameter.device)) + return model + + +def _self_comm_dict(nloc: int, mapping: np.ndarray, keepalive: list) -> dict: + """Return a one-swap self-send plan that copies every owner to its ghosts.""" + send_list = np.ascontiguousarray(mapping[nloc:], dtype=np.int32) + keepalive.append(send_list) + nghost = len(send_list) + address = send_list.ctypes.data_as(ctypes.c_void_p).value + return { + "send_list": torch.tensor([address], dtype=torch.int64), + "send_proc": torch.zeros(1, dtype=torch.int32), + "recv_proc": torch.zeros(1, dtype=torch.int32), + "send_num": torch.tensor([nghost], dtype=torch.int32), + "recv_num": torch.tensor([nghost], dtype=torch.int32), + "communicator": torch.zeros(1, dtype=torch.int64), + "nlocal": torch.tensor(nloc, dtype=torch.int32), + "nghost": torch.tensor(nghost, dtype=torch.int32), + } + + +def _run_folded(model: torch.nn.Module, coord: np.ndarray) -> tuple: + graph = build_neighbor_graph( + coord, ATYPE, (BOX * np.eye(3)).reshape(1, 3, 3), RCUT, canonicalize=True + ) + n_node = torch.as_tensor(np.asarray(graph.n_node), dtype=torch.int64) + out = model.forward_common_lower_graph( + torch.tensor(ATYPE.reshape(-1), dtype=torch.int64), + n_node, + n_node, + torch.as_tensor(np.asarray(graph.edge_index), dtype=torch.int64), + torch.as_tensor(np.asarray(graph.edge_vec), dtype=torch.float64), + torch.as_tensor(np.asarray(graph.edge_mask), dtype=torch.bool), + ) + energy = out["energy_redu"].detach().numpy().reshape(-1) + force = -out["energy_derv_r"].detach().numpy().reshape(-1, 3) + return energy, force + + +def _run_self_comm(model: torch.nn.Module, coord: np.ndarray) -> tuple: + nloc = ATYPE.shape[1] + ext_coord, ext_atype, mapping = extend_coord_with_ghosts( + coord, ATYPE, (BOX * np.eye(3)).reshape(1, 9), RCUT + ) + nlist = np.asarray( + build_neighbor_list( + ext_coord, ext_atype, nloc, RCUT, [256], distinguish_types=False + ) + )[0] + ext_coord = np.asarray(ext_coord).reshape(-1, 3) + mapping = np.asarray(mapping)[0] + valid = nlist >= 0 + src = nlist[valid].astype(np.int64) + dst = np.repeat(np.arange(nloc, dtype=np.int64), nlist.shape[1])[valid.ravel()] + keepalive: list = [] + out = model.forward_common_lower_graph( + torch.tensor(np.asarray(ext_atype)[0], dtype=torch.int64), + torch.tensor([ext_coord.shape[0]], dtype=torch.int64), + torch.tensor([nloc], dtype=torch.int64), + torch.tensor(np.stack([src, dst]), dtype=torch.int64), + torch.tensor(ext_coord[src] - ext_coord[dst], dtype=torch.float64), + torch.ones(len(src), dtype=torch.bool), + comm_dict=_self_comm_dict(nloc, mapping, keepalive), + ) + energy = out["energy_redu"].detach().numpy().reshape(-1) + ghost_force = -out["energy_derv_r"].detach().numpy().reshape(-1, 3) + force = np.zeros((nloc, 3)) + np.add.at(force, mapping, ghost_force) + return energy, force + + +@pytest.mark.parametrize( + "config", + [CONFIG, ZBL_CONFIG, THREE_BLOCK_CONFIG], + ids=["plain", "bridged", "three_blocks"], +) +class TestMultiBlockSelfComm: + @pytest.fixture(autouse=True) + def _setup(self, config: dict) -> None: + ensure_comm_registered() + self.model = _perturb(get_model(copy.deepcopy(config)).to("cpu").eval()) + # Atoms 0 and 1 face each other across the periodic x boundary at + # 0.9 Å, inside the window of the bridged model. + self.coord = COORD + + def test_exchange_matches_the_folded_graph(self) -> None: + energy, force = _run_folded(self.model, self.coord) + exchanged_energy, exchanged_force = _run_self_comm(self.model, self.coord) + np.testing.assert_allclose(exchanged_energy, energy, rtol=1e-12, atol=1e-12) + np.testing.assert_allclose(exchanged_force, force, rtol=1e-11, atol=1e-11) + + def test_identity_exchange_diverges(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Without refreshing the ghost rows the parity breaks.""" + from deepmd.pt_expt.descriptor import dpa4c as module + + monkeypatch.setattr( + module.DescrptDPA4C, + "exchange_ghost_rows", + lambda self, values, comm_dict: values, + ) + energy, _ = _run_folded(self.model, self.coord) + exchanged_energy, _ = _run_self_comm(self.model, self.coord) + assert np.abs(exchanged_energy - energy).max() > 1e-6 + + +def test_source_gate_needs_its_cross_rank_completion( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The close pair straddles the boundary, so its gate partials do too.""" + from deepmd.pt_expt.descriptor import dpa4c as module + + ensure_comm_registered() + model = _perturb(get_model(copy.deepcopy(ZBL_CONFIG)).to("cpu").eval()) + energy, _ = _run_folded(model, COORD) + monkeypatch.setattr( + module.DescrptDPA4C, + "complete_node_partials", + lambda self, partials, comm_dict: partials, + ) + exchanged_energy, _ = _run_self_comm(model, COORD) + assert np.abs(exchanged_energy - energy).max() > 1e-6 + + +@pytest.mark.parametrize("config", [CONFIG, ZBL_CONFIG], ids=["plain", "bridged"]) +def test_with_comm_export_traces_the_exchange(config: dict) -> None: + """A multi-block model freezes a with-comm program that refreshes ghosts.""" + from deepmd.pt_expt.utils.serialization import ( + _needs_with_comm_artifact, + _trace_and_export, + ) + + ensure_comm_registered() + model = _perturb(get_model(copy.deepcopy(config)).to("cpu").eval()) + assert _needs_with_comm_artifact(model, lower_kind="graph") + exported, _metadata, _model_json, _keys = _trace_and_export( + {"model": model.serialize()}, + model_json_override=None, + with_comm_dict=True, + lower_kind="graph", + ) + code = str(exported.module().code) + assert "deepmd_export.border_op" in code + if "bridging_method" in config: + assert "deepmd_export.border_op_backward" in code + + +def test_single_block_needs_no_with_comm_artifact() -> None: + single = copy.deepcopy(CONFIG) + single["descriptor"].update(rcut=RCUT, n_blocks=1) + from deepmd.pt_expt.utils.serialization import ( + _needs_with_comm_artifact, + ) + + assert not _needs_with_comm_artifact(get_model(single), lower_kind="graph") diff --git a/source/tests/pt_expt/model/test_dpa4c_zbl_bridging.py b/source/tests/pt_expt/model/test_dpa4c_zbl_bridging.py index 150bb5d8fd..2706caba76 100644 --- a/source/tests/pt_expt/model/test_dpa4c_zbl_bridging.py +++ b/source/tests/pt_expt/model/test_dpa4c_zbl_bridging.py @@ -3,15 +3,20 @@ ``bridging_method: zbl`` on a DPA4C model builds the same linear composition as DPA4 (``LinearEnergyModel`` over ``[learned, InnerPotentialAtomicModel]``). -DPA4C has no message passing and carries the edge envelope in every edge term, -so its bridging window is one inner switch on that envelope, paired with a -clamp of the length the radial features read: a pair at or below the inner -radius leaves the learned model exactly as if its edge were deleted, and the -analytical term supplies the whole pair interaction. +A single-block DPA4C carries the edge envelope in every edge term, so its +bridging window is one inner switch on that envelope, paired with a clamp of +the length the radial features read: a pair at or below the inner radius +leaves the learned model exactly as if its edge were deleted, and the +analytical term supplies the whole pair interaction. A further block that +reads its neighbors adds the source gate of DPA4, which keeps the pair out of +every third environment. """ import copy import math +from typing import ( + ClassVar, +) import numpy as np import pytest @@ -268,6 +273,78 @@ def test_pair_table_is_rebuilt_not_stored(self) -> None: ) +class TestDPA4CZBLBridgingMultiBlock: + """A further block that reads its neighbors keeps the frozen pair out. + + The neighbor state of a third atom sees both atoms of a close pair, so + without the source gate it would hand the pair back to either atom. The + gate mutes every edge a frozen atom emits towards a third atom, so both + atoms of the pair leave every other environment. + """ + + MULTI_BLOCK: ClassVar[dict] = {"rcut": [4.0, 3.5], "n_blocks": 2} + + def setup_method(self) -> None: + config = copy.deepcopy(ZBL_CONFIG) + config["descriptor"].update(self.MULTI_BLOCK) + self.model = get_model(config).eval() + _perturb(self.model) + + def _learned_twin(self, window: bool) -> torch.nn.Module: + """The learned child as a standalone model, with or without its window.""" + config = copy.deepcopy(PLAIN_CONFIG) + config["descriptor"].update(self.MULTI_BLOCK) + if window: + config["descriptor"].update( + inner_clamp_f_inner=R_INNER, + inner_clamp_f_outer=R_OUTER, + inner_clamp_scale="absolute", + ) + twin = get_model(config).eval() + twin.atomic_model.load_state_dict( + self.model.atomic_model.models[0].state_dict() + ) + return twin + + @staticmethod + def _atom_energy(model: torch.nn.Module, coord: np.ndarray) -> np.ndarray: + return _evaluate(model, coord)["atom_energy"].detach().cpu().numpy()[0, :, 0] + + @pytest.mark.parametrize("distance", [0.2, 0.45]) + def test_frozen_pair_does_not_reach_the_other_atoms(self, distance: float) -> None: + coord = _cluster(distance) + moved = coord.copy() + moved[1] = coord[0] + distance * np.array([0.0, -0.6, 0.8]) + windowed = self._learned_twin(window=True) + delta = self._atom_energy(windowed, moved) - self._atom_energy(windowed, coord) + # The learned energies of the O atom and of both third atoms ignore + # where the He atom sits inside the frozen zone, while the He atom + # sees its own new environment. + np.testing.assert_allclose(delta[[0, 2, 3]], 0.0, atol=1e-12) + assert abs(delta[1]) > 1e-6 + # Without the window the third atoms read the motion of the He atom, + # so the contract is not vacuous. + plain = self._learned_twin(window=False) + plain_delta = self._atom_energy(plain, moved) - self._atom_energy(plain, coord) + assert np.abs(plain_delta[[2, 3]]).max() > 1e-6 + + @pytest.mark.parametrize("distance", [0.3, 0.5, 0.65, 0.8, 1.1]) + def test_force_matches_finite_difference(self, distance: float) -> None: + coord = _cluster(distance) + force = _evaluate(self.model, coord)["force"] + step = 1.0e-5 + for atom in (0, 1, 2): + for axis in range(3): + shift = np.zeros_like(coord) + shift[atom, axis] = step + upper = _evaluate(self.model, coord + shift)["energy"].item() + lower = _evaluate(self.model, coord - shift)["energy"].item() + expected = -(upper - lower) / (2.0 * step) + assert force[0, atom, axis].item() == pytest.approx( + expected, rel=1e-6, abs=1e-6 + ) + + def _native_spin(base: dict) -> dict: """The same configuration with a magnetic moment on every type.""" return { diff --git a/source/tests/pt_expt/model/test_long_range.py b/source/tests/pt_expt/model/test_long_range.py index 0581dd8626..ca5b8d03cd 100644 --- a/source/tests/pt_expt/model/test_long_range.py +++ b/source/tests/pt_expt/model/test_long_range.py @@ -28,6 +28,8 @@ from deepmd.pt_expt.entrypoints.main import ( change_bias, ) +from deepmd.pt_expt.kernels import long_range as long_range_kernels +from deepmd.pt_expt.kernels.dpa4c import canonical as dpa4c_canonical from deepmd.pt_expt.model.get_model import ( get_model, ) @@ -47,6 +49,7 @@ from deepmd.pt_expt.utils.serialization import ( check_mesh_compile_torch_version, check_mesh_freeze_torch_version, + compressed_export_unsupported_reason, deserialize_to_file, mesh_compile_supported, mesh_freeze_supported, @@ -1120,6 +1123,335 @@ def test_compressed_frozen_model_matches_uncompressed( ) +def _two_block_config( + kernel: str, periodic: bool, width: int = 32, charge: tuple[int, ...] = (16, 16) +) -> dict: + """Return a compressible model of two blocks whose long-range module the fused operator serves. + + The second block reads a cutoff below that of the first, and the charge + network has one channel, which the fused fitting kernels reproduce. The + energy fitting has two hidden layers of ``width`` and the charge network + the hidden layers ``charge``. + """ + config = _config(kernel, constraint=NEUTRAL if kernel == "les" else None) + config["descriptor"].update( + n_radial=8, precision="float32", n_blocks=2, rcut=[3.0, 2.5] + ) + config["fitting_net"].update( + neuron=[width, width], activation_function="silu", resnet_dt=False + ) + config["fitting_net"]["precision"] = "float32" + config["long_range"].update( + channels=1, + charge_net={"neuron": list(charge), "seed": 23}, + periodic=periodic, + ) + if kernel == "sog": + config["long_range"]["kernel"] = {"type": "sog", "n_gaussian": 4} + return config + + +def _perturbed_model(config: dict) -> torch.nn.Module: + """Build the model of ``config`` with every parameter moved off its initial value.""" + model = get_model(config).to(env.DEVICE).eval() + generator = torch.Generator().manual_seed(5) + with torch.no_grad(): + for parameter in model.parameters(): + noise = torch.randn(parameter.shape, generator=generator) + parameter.add_(0.05 * noise.to(parameter)) + return model + + +@pytest.mark.parametrize("periodic", [False, True]) +@pytest.mark.parametrize("kernel", ["les", "sog"]) +def test_compressed_further_blocks_with_long_range_match_uncompressed( + tmp_path, kernel: str, periodic: bool +) -> None: + """A compressed model of two blocks keeps its long-range module through the freeze. + + On a CUDA device the freeze selects the compact canonical lower, whose + fused long-range operator evaluates the further block between the first + block and the charges; on the CPU the graph lower evaluates the equations + of the descriptor. Both match the uncompressed model on a cluster and, for + a periodic module, on the mesh of a periodic frame. + """ + if periodic and env.DEVICE.type != "cuda" and not mesh_freeze_supported(): + pytest.skip(f"torch {torch.__version__} cannot package the mesh evaluation") + config = _two_block_config(kernel, periodic) + model = _perturbed_model(config) + reference = copy.deepcopy(model) + if periodic: + reference.atomic_model.long_range.use_mesh_evaluation() + model.atomic_model.enable_compression(0.5) + frozen = tmp_path / f"two_block_long_range_{kernel}.pt2" + deserialize_to_file( + str(frozen), + {"model": model.serialize(), "model_def_script": config}, + do_atomic_virial=True, + lower_kind="auto", + ) + dp = DeepPot(str(frozen), auto_batch_size=False) + expected_lower = "dpa4c_canonical" if env.DEVICE.type == "cuda" else "graph" + assert dp.deep_eval.metadata["lower_input_kind"] == expected_lower + rng = np.random.default_rng(3) + atype = rng.integers(0, 2, (1, 40)) + frames = [(rng.uniform(0.0, 7.0, (1, 40, 3)) + 100.0, None)] + if periodic: + box = np.array([[[12.0, 0.0, 0.0], [0.8, 11.0, 0.0], [-0.5, 0.6, 13.0]]]) + frames.append((rng.uniform(0.0, 1.0, (1, 40, 3)) @ box[0], box)) + names = ("energy", "force", "virial", "atom_energy", "atom_virial") + for coord, cell in frames: + expected = reference( + _tensor(coord), + _tensor(atype, torch.int64), + box=None if cell is None else _tensor(cell), + do_atomic_virial=True, + ) + actual = dp.eval(coord, cell, atype, atomic=True) + atom_energy = expected["atom_energy"].detach().cpu().numpy() + for name, value in zip(names, actual, strict=True): + target = expected[name].detach().cpu().numpy().reshape(value.shape) + # The energy of a frame sums atomic energies, whose long-range + # parts may cancel between atoms of either sign, so its error is + # bounded by their relative error times the sum of their + # magnitudes, which equals the magnitude of the sum when they share + # a sign. + scale = ( + np.abs(atom_energy).sum() if name == "energy" else np.abs(target).max() + ) + # The tables of the compressed descriptor approximate its + # networks, to a few 1e-6 of the scale of every output. + assert np.abs(value - target).max() <= 2e-5 * scale + 1e-5, ( + name, + cell is None, + np.abs(value - target).max(), + scale, + ) + + +@pytest.mark.skipif( + env.DEVICE.type != "cuda", reason="the compact canonical path is CUDA only" +) +def test_compressed_further_blocks_need_the_fused_long_range_operator( + tmp_path, +) -> None: + """A compressed model of two blocks with a charge network of three channels is refused. + + The fused long-range operator evaluates the further blocks with a charge + network of one channel; the composition of operators that serves a + network of three channels evaluates one block, so the deployment of such + a model on the CUDA backend stops with a diagnostic instead of falling + back to the uncompressed equations of a generic lower. The model differs + from one that the fused operator serves in its channel count alone. + """ + config = _two_block_config("sog", periodic=False) + config["long_range"]["channels"] = 3 + model = get_model(config).to(env.DEVICE).eval() + model.atomic_model.enable_compression(0.5) + with pytest.raises(ValueError, match="fused long-range operator"): + deserialize_to_file( + str(tmp_path / "two_block_three_channels.pt2"), + {"model": model.serialize(), "model_def_script": config}, + lower_kind="auto", + ) + + +@pytest.mark.parametrize( + ("case", "refused"), + [("one_channel", False), ("three_channels", True), ("charge_state", False)], +) +def test_a_freeze_judges_a_long_range_model_as_compressed( + monkeypatch, case: str, refused: bool +) -> None: + """A freeze judges a model of two blocks with a long-range module as its compression leaves it. + + The judgment before compression, from which the automatic freeze of the + ASE calculator decides whether to compress, is that of the compressed + model: a charge network of three channels is refused in both, and a + constraint that reads the charge state of each frame is served, since the + compression of the model folds that state. The judgment reads the + configuration and the operators of the library, so the test targets CUDA + with the operators present on any device. + """ + monkeypatch.setattr(dpa4c_canonical, "backend_device_type", lambda: "cuda") + monkeypatch.setattr(dpa4c_canonical, "operator_available", lambda name: True) + monkeypatch.setattr(long_range_kernels, "op_available", lambda: True) + config = _two_block_config( + "sog" if case == "three_channels" else "les", periodic=False + ) + if case == "three_channels": + config["long_range"]["channels"] = 3 + elif case == "charge_state": + config["descriptor"].update(add_chg_spin_ebd=True, default_chg_spin=[1, 2]) + config["long_range"]["charge_constraint"] = {"source": "charge_spin"} + model = get_model(config).to("cpu").eval() + before = compressed_export_unsupported_reason(model) + model.atomic_model.enable_compression(0.5) + after = dpa4c_canonical.canonical_model_unsupported_reason(model) + assert (before is not None) == (after is not None) == refused, (before, after) + + +@pytest.mark.skipif( + env.DEVICE.type != "cuda", reason="the compact canonical lower is CUDA only" +) +@pytest.mark.parametrize("layout", ["per_layer", "fused"]) +@pytest.mark.parametrize("tile", [0, 16]) +@pytest.mark.parametrize("kernel", ["les", "sog"]) +def test_further_blocks_with_long_range_read_halo_rows( + monkeypatch, kernel: str, tile: int, layout: str +) -> None: + """A node set with halo rows evaluates a model of two blocks and its long range like the folded frame. + + The owned atoms of a periodic frame keep complete rows, and every periodic + image within the cutoff of an owned atom becomes a halo row without edges + and without charge, which one self swap of the border plan refreshes from + its owner before every further block. The fused long-range operator + evaluates the owned rows, their charges and the mesh sum of the cell, in + one run or in runs of 16 rows, whose descriptor rows the charges read + together, with both networks on the per-layer kernels or on the fused + network (``FUSED_LAYOUTS``); the forces and the per-atom virials of the + halo rows, folded onto their owners, and every other output match those + of the folded frame evaluated in one run, in which every edge leads from + the owner itself. + """ + from deepmd.dpmodel.utils.neighbor_graph import ( + NeighborGraph, + attach_edge_csr, + ) + from deepmd.pt_expt.kernels.graph_fitting import ( + fitting_operator_arguments, + ) + from deepmd.pt_expt.utils.canonical_graph import ( + BorderPlan, + canonical_graph_from_neighbor_graph, + ) + + shape = FUSED_LAYOUTS[layout] + model = _perturbed_model( + _two_block_config( + kernel, periodic=True, width=shape["width"], charge=shape["charge"] + ) + ) + model.atomic_model.long_range.use_mesh_evaluation() + model.atomic_model.enable_compression(0.5) + owned, side = 40, 8.0 + # The rules of the fitting routes take the network of the layout on every + # run of the owned rows; a device on which they send the runs of the fused + # layout to the per-layer kernels has no fused network to evaluate. + runs = {owned} if tile == 0 else {tile, owned % tile or tile} + routes = [ + int( + torch.ops.deepmd.graph_fitting_route_rule( + fitting_operator_arguments(network).weights, n + ) + ) + for network in ( + model.atomic_model.fitting_net, + model.atomic_model.long_range.charge_net, + ) + for n in runs + ] + if layout == "fused" and -1 in routes: + pytest.skip("the fitting rules take the per-layer kernels on this device") + assert all((route == -1) == (layout == "per_layer") for route in routes), routes + rng = np.random.default_rng(11) + local = rng.uniform(0.0, side, (owned, 3)) + atype = rng.integers(0, 2, owned) + cell = np.eye(3) * side + atype_t, graph, coord_t, box_t = _canonical_inputs( + model, local[None], atype[None], cell[None] + ) + + def evaluate(graph, atype_t, coord_t, **border) -> dict[str, torch.Tensor]: + return model.forward_lower_canonical_graph( + atype_t, + graph.n_node, + graph.n_local, + graph.source, + graph.edge_vec, + graph.destination_row_ptr, + graph.source_row_ptr, + graph.source_order, + do_atomic_virial=True, + coord=coord_t, + box=box_t, + **border, + ) + + monkeypatch.setenv("DP_NODE_TILE", "0") + expected = evaluate(graph, atype_t, coord_t) + monkeypatch.setenv("DP_NODE_TILE", str(tile)) + + # The node set: the owned atoms, then their images within the cutoff of + # the first block of an owned atom, as halo rows. + rcut = model.get_rcut() + points = _tensor(local) + shifts = torch.cartesian_prod(*[torch.tensor([-1.0, 0.0, 1.0])] * 3) + shifts = side * shifts[shifts.abs().sum(-1) > 0].to(points) + images = (points[None] + shifts[:, None]).reshape(-1, 3) + near = ( + torch.cdist(images, points, compute_mode="donot_use_mm_for_euclid_dist") + .amin(-1) + .lt(rcut) + ) + points = torch.cat((points, images[near])) + local_index = torch.arange(owned, device=env.DEVICE) + owner = torch.cat((local_index, local_index.repeat(shifts.shape[0])[near])) + distance = torch.cdist( + points[:owned], points, compute_mode="donot_use_mm_for_euclid_dist" + ) + destination, source = torch.nonzero( + (distance < rcut) & (distance > 1e-8), as_tuple=True + ) + node_count = points.shape[0] + halo_graph = canonical_graph_from_neighbor_graph( + attach_edge_csr( + NeighborGraph( + n_node=torch.tensor([node_count], device=env.DEVICE), + edge_index=torch.stack((source, destination)), + edge_vec=(points[source] - points[destination]).to(torch.float32), + edge_mask=torch.ones( + source.shape[0], dtype=torch.bool, device=env.DEVICE + ), + n_local=torch.tensor([owned], device=env.DEVICE), + ), + node_count, + canonicalize=True, + ) + ) + halo = node_count - owned + plan = BorderPlan( + send_nodes=owner[owned:].to(torch.int32).contiguous(), + swaps=torch.tensor([[0, 0, halo, halo, owned]], dtype=torch.int32), + communicator=torch.zeros(1, dtype=torch.int64), + ) + actual = evaluate( + halo_graph, + atype_t[owner], + points, + communicator=plan.communicator, + halo_send=plan.send_nodes, + halo_swaps=plan.swaps, + ) + folded = { + "energy": actual["energy"], + "virial": actual["virial"], + "atom_energy": actual["atom_energy"][:owned], + "force": actual["force"] + .new_zeros(owned, 3) + .index_add_(0, owner, actual["force"]), + "atom_virial": actual["atom_virial"] + .new_zeros(owned, 3, 3) + .index_add_(0, owner, actual["atom_virial"].reshape(-1, 3, 3)), + } + for key, value in folded.items(): + # Both evaluate in float32 and sum the halo rows in another order. + reference = expected[key].detach().to(torch.float64).reshape(value.shape) + error = (value.detach().to(torch.float64) - reference).abs().max() + scale = reference.abs().max() + assert error <= 1e-5 * scale + 1e-6, (key, error.item(), scale.item()) + + @pytest.mark.parametrize("kernel", ["les", "sog"]) @REQUIRES_SUPPORTED_COMPILE def test_compiled_matches_eager(kernel: str) -> None: diff --git a/source/tests/pt_expt/test_freeze_compress.py b/source/tests/pt_expt/test_freeze_compress.py index d1a9407b22..4daa60ce32 100644 --- a/source/tests/pt_expt/test_freeze_compress.py +++ b/source/tests/pt_expt/test_freeze_compress.py @@ -29,6 +29,7 @@ ) from deepmd.pt_expt.entrypoints import compress as compression from deepmd.pt_expt.entrypoints import main as entrypoints +from deepmd.pt_expt.kernels.dpa4c import canonical as dpa4c_canonical from deepmd.pt_expt.model.get_model import ( get_model, ) @@ -176,9 +177,14 @@ def capture(model_file: str, data: dict, **kwargs: object) -> None: assert checkpoint.read_bytes() == original -@pytest.mark.parametrize("case", ["precision", "exclusions", "charge_state", "widths"]) +@pytest.mark.parametrize( + "case", ["precision", "exclusions", "charge_state", "widths", "blocks"] +) def test_ase_falls_back_but_explicit_compression_reports_ineligibility( - tmp_path: Path, caplog: pytest.LogCaptureFixture, case: str + tmp_path: Path, + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, + case: str, ) -> None: config = _config("dpa4c") if case == "precision": @@ -191,6 +197,13 @@ def test_ase_falls_back_but_explicit_compression_reports_ineligibility( elif case == "widths": config["descriptor"]["radial_modes"] = 3 error = "radial_modes" + elif case == "blocks": + # On a CUDA target, the compact canonical operators alone evaluate a + # compressed model of several blocks, and they exclude no type pair. + monkeypatch.setattr(dpa4c_canonical, "backend_device_type", lambda: "cuda") + config["descriptor"]["n_blocks"] = 2 + config["pair_exclude_types"] = [[0, 1]] + error = "pair_exclude_types" else: config["descriptor"]["add_chg_spin_ebd"] = True config["descriptor"]["default_chg_spin"] = None diff --git a/source/tests/pt_expt/utils/test_canonical_graph.py b/source/tests/pt_expt/utils/test_canonical_graph.py index b59a71fee3..356391233c 100644 --- a/source/tests/pt_expt/utils/test_canonical_graph.py +++ b/source/tests/pt_expt/utils/test_canonical_graph.py @@ -1,9 +1,17 @@ # SPDX-License-Identifier: LGPL-3.0-or-later +from dataclasses import ( + replace, +) +from unittest import ( + mock, +) + import pytest import torch from deepmd.dpmodel.utils.neighbor_graph import ( NeighborGraph, + build_neighbor_graph, ) from deepmd.pt_expt.utils.canonical_graph import ( INT32_MAX, @@ -13,6 +21,7 @@ canonical_index_bytes, canonical_index_words, validate_canonical_graph_shapes, + validate_reciprocal_canonical_graph, ) @@ -54,6 +63,100 @@ def test_storage_guards_remain_outside_csr(physical_edge_count: int) -> None: validate_canonical_graph_shapes(compact, 1) +def test_reciprocity_checks_periodic_images_and_duplicate_counts() -> None: + center = torch.tensor([0, 0, 1, 1, 0, 0]) + source = torch.tensor([1, 1, 0, 0, 0, 0]) + vector = torch.tensor( + [ + [1.0, 0.0, 0.0], + [-2.0, 0.0, 0.0], + [2.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + [3.0, 0.0, 0.0], + [-3.0, 0.0, 0.0], + ] + ) + for count in (0, 4, 6): + graph = canonical_graph_from_pairs( + center[:count], source[:count], vector[:count], torch.tensor([2]), 2 + ) + validate_reciprocal_canonical_graph(graph) + for count in (1, 3, 5): + graph = canonical_graph_from_pairs( + center[:count], source[:count], vector[:count], torch.tensor([2]), 2 + ) + with pytest.raises(ValueError, match="bidirectional"): + validate_reciprocal_canonical_graph(graph) + vector[2] = vector[3] + graph = canonical_graph_from_pairs(center, source, vector, torch.tensor([2]), 2) + with pytest.raises(ValueError, match="bidirectional"): + validate_reciprocal_canonical_graph(graph) + + +def test_reciprocity_matching_accepts_periodic_roundoff() -> None: + graph = canonical_graph_from_pairs( + torch.tensor([0, 0, 1, 1]), + torch.tensor([1, 1, 0, 0]), + torch.tensor( + [[1e-7, 1.0, 0.0], [0.0, 2.0, 0.0], [0.0, -1.0, 0.0], [-1e-7, -2.0, 0.0]] + ), + torch.tensor([2]), + 2, + ) + validate_reciprocal_canonical_graph(graph) + + +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_periodic_self_images_are_matched_without_host_transfers(device: str) -> None: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA is required") + coord = torch.zeros(4, 1, 3, dtype=torch.float64, device=device) + types = torch.zeros(4, 1, dtype=torch.int64, device=device) + box = 1.5 * torch.eye(3, dtype=torch.float64, device=device).repeat(4, 1, 1) + neighbor = build_neighbor_graph(coord, types, box, 2.0, canonicalize=True) + graph = canonical_graph_from_neighbor_graph( + replace(neighbor, n_local=neighbor.n_node) + ) + with mock.patch.object( + torch.Tensor, "cpu", side_effect=AssertionError("host transfer") + ): + validate_reciprocal_canonical_graph(graph) + + +@pytest.mark.parametrize("device", ["cpu", "cuda"]) +def test_only_ambiguous_image_groups_reach_host_matching(device: str) -> None: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA is required") + center = torch.tensor([0, 0, 1, 1, 2, 3, 4, 4], device=device) + source = torch.tensor([1, 1, 0, 0, 3, 2, 4, 4], device=device) + vector = torch.tensor( + [ + [1e-7, 1.0, 0.0], + [0.0, 2.0, 0.0], + [0.0, -1.0, 0.0], + [-1e-7, -2.0, 0.0], + [0.5, 0.0, 0.0], + [-0.5, 0.0, 0.0], + [1.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + ], + device=device, + ) + graph = canonical_graph_from_pairs( + center, source, vector, torch.tensor([5], device=device), 5 + ) + cpu = torch.Tensor.cpu + transfers = [] + + def record_transfer(tensor: torch.Tensor) -> torch.Tensor: + transfers.append(tuple(tensor.shape)) + return cpu(tensor) + + with mock.patch.object(torch.Tensor, "cpu", record_transfer): + validate_reciprocal_canonical_graph(graph) + assert [shape for shape in transfers if len(shape) == 2] == [(4, 3), (4, 3)] + + @pytest.mark.parametrize("index_dtype", [torch.uint32, torch.int64]) def test_edge_storage_range_is_independent_of_node_width( index_dtype: torch.dtype, diff --git a/source/tests/test_cc_local.py b/source/tests/test_cc_local.py index ae33f10a06..ff045d2cbb 100644 --- a/source/tests/test_cc_local.py +++ b/source/tests/test_cc_local.py @@ -172,6 +172,7 @@ def wait_for_event(event, model): "MOCK_SCHEDULE_DIR": str(tmp_path / "schedule"), "MOCK_SCHEDULE_LOG": str(tmp_path / "schedule.jsonl"), "MOCK_CHECK_SCHEDULE": "", + "LAMMPS_VERSION": "", } Path(env["MOCK_SCHEDULE_DIR"]).mkdir() return root, script, env @@ -244,6 +245,7 @@ def test_default_still_builds_all_models_and_runs_ctest(build_tree): result, commands = run_script(build_tree) assert result.returncode == 0, result.stderr assert "BUILD_TESTING:BOOL=TRUE" in commands[0]["args"] + assert "LAMMPS_VERSION=stable_22Jul2025_update2" in commands[0]["args"] assert [c["name"] for c in commands[:4]] == ["cmake", "cmake", "cmake", "python"] assert commands[1]["args"][:2] == ["--build", "."] assert commands[2]["args"] == ["--install", "."] @@ -342,7 +344,20 @@ def test_build_only_installs_without_generating_models_or_running_ctest( ) -def test_kokkos_models_reuse_build_and_preserve_other_fixtures(build_tree): +def test_build_only_honors_explicit_lammps_version( + build_tree: tuple[Path, Path, dict[str, str]], +) -> None: + result, commands = run_script( + build_tree, "--build-only", LAMMPS_VERSION="patch_4Jul2026" + ) + assert result.returncode == 0, result.stderr + assert "LAMMPS_VERSION=patch_4Jul2026" in commands[0]["args"] + assert not generated_models(commands) + + +def test_kokkos_models_reuse_build_and_preserve_other_fixtures( + build_tree: tuple[Path, Path, dict[str, str]], +) -> None: root, _, _ = build_tree infer = root / "source/tests/infer" keep = infer / "other_model.pt2" @@ -355,14 +370,22 @@ def test_kokkos_models_reuse_build_and_preserve_other_fixtures(build_tree): path.touch() result, commands = run_script(build_tree, "--models-only=kokkos") assert result.returncode == 0, result.stderr - assert [c["name"] for c in commands] == ["python", "python"] + assert [c["name"] for c in commands] == ["python", "python", "python"] assert commands[0]["args"][0] == "-c" - assert generated_models(commands) == ["gen_dpa4c_long_range.py"] + assert generated_models(commands) == [ + "gen_dpa4c_long_range.py", + "gen_dpa4c_canonical.py", + ] assert commands[1]["args"][0] == "-u" assert commands[1]["args"][2:] == ["--compressed-only"] + assert commands[2]["args"][0] == "-u" + assert commands[2]["args"][2:] == [] reports = generator_reports(root) - assert len(reports) == 1 - assert {path.stem for path in reports} == {"gen_dpa4c_long_range"} + assert len(reports) == 2 + assert {path.stem for path in reports} == { + "gen_dpa4c_long_range", + "gen_dpa4c_canonical", + } assert {row["exit_status"] for row in reports.values()} == {"0"} assert not (root / "source/build_tests/gtest-reports").exists() assert ( @@ -422,15 +445,18 @@ def test_default_propagates_generator_failures(build_tree, model): assert "gen_corrupt_with_comm.py" not in generated_models(commands) -def test_kokkos_models_propagate_generator_failure(build_tree): +@pytest.mark.parametrize("model", ["gen_dpa4c_long_range.py", "gen_dpa4c_canonical.py"]) +def test_kokkos_models_propagate_generator_failure( + build_tree: tuple[Path, Path, dict[str, str]], model: str +) -> None: root, _, _ = build_tree - result, _ = run_script( - build_tree, "--models-only=kokkos", MOCK_FAIL="gen_dpa4c_long_range.py" - ) + result, _ = run_script(build_tree, "--models-only=kokkos", MOCK_FAIL=model) assert result.returncode == 17 - reports = generator_reports(root) - assert len(reports) == 1 - assert {row["exit_status"] for row in reports.values()} == {"17"} + reports = {path.stem: row for path, row in generator_reports(root).items()} + assert len(reports) == (1 if model == "gen_dpa4c_long_range.py" else 2) + assert reports[Path(model).stem]["exit_status"] == "17" + if model == "gen_dpa4c_canonical.py": + assert reports["gen_dpa4c_long_range"]["exit_status"] == "0" @pytest.mark.parametrize( diff --git a/source/tests/test_cpp_ci_reports.py b/source/tests/test_cpp_ci_reports.py index 0d78ccb9cc..8ff11d5b06 100644 --- a/source/tests/test_cpp_ci_reports.py +++ b/source/tests/test_cpp_ci_reports.py @@ -223,6 +223,18 @@ def test_kokkos_pytest_processes_write_distinct_reports(): assert script.startswith("#!/bin/bash\nset -euxo pipefail\n") +def test_kokkos_uses_a_fixed_spin_capable_lammps_release() -> None: + config = yaml.safe_load((ROOT / ".github/workflows/test_cuda.yml").read_text()) + steps = config["jobs"]["test_cc"]["steps"] + overrides = [step for step in steps if "LAMMPS_VERSION" in step.get("env", {})] + assert len(overrides) == 1 + assert overrides[0]["if"] == "matrix.suite == 'kokkos'" + assert overrides[0]["env"]["LAMMPS_VERSION"] == "patch_4Jul2026" + assert "source/install/test_cc_local.sh --build-only" in overrides[0]["run"] + script = (ROOT / "source/install/test_lammps_kokkos.sh").read_text() + assert script.count("-D CMAKE_CXX_STANDARD=20") == 2 + + @pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") @pytest.mark.parametrize("status", [0, 17]) def test_kokkos_spin_generator_reports_preserve_status_and_invocations( @@ -277,7 +289,9 @@ def test_kokkos_spin_generator_reports_preserve_status_and_invocations( @pytest.mark.skipif(sys.platform != "linux", reason="Requires GNU/Linux shell tools") @pytest.mark.parametrize("failure", ["", "spin.xml", "long-range.xml"]) -def test_kokkos_report_commands_preserve_pytest_status(tmp_path, failure): +def test_kokkos_report_commands_preserve_pytest_status( + tmp_path: Path, failure: str +) -> None: # Execute the unmodified test-command tail with a tiny pytest stand-in. # This tests exit-status/report wiring, not the CUDA/LAMMPS computation. script = (ROOT / "source/install/test_lammps_kokkos.sh").read_text() @@ -291,6 +305,11 @@ def test_kokkos_report_commands_preserve_pytest_status(tmp_path, failure): "from pathlib import Path\n" "assert sys.argv[1:3] == ['-m', 'pytest']\n" "report = Path(next(a.split('=', 1)[1] for a in sys.argv if a.startswith('--junitxml=')))\n" + "expected = {\n" + " 'spin.xml': {'test_dpa4spin_kokkos_magnetic_force.py', 'test_lammps_dpa4c_multiblock_kokkos.py'},\n" + " 'long-range.xml': {'test_lammps_dpa4c_long_range_kokkos.py'},\n" + "}\n" + "assert {Path(a).name for a in sys.argv if a.endswith('.py')} == expected[report.name]\n" "report.write_text('')\n" "sys.exit(17 if report.name == os.environ['MOCK_FAIL'] else 0)\n" )