Datasets:

ArXiv:
License:
File size: 10,238 Bytes
38ad8a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Copyright (c) 2021 The President and Fellows of Harvard College
# Copyright (c) 2025 The NequIP Developers
# Copyright (c) 2025 ByteDance Ltd. and/or its affiliates
# SPDX-License-Identifier: MIT
#
# This file has been modified by ByteDance Ltd. and/or its affiliates on 2025-09-01.
#
# Original file was released under MIT, with the full license text
# available at https://github.com/mir-group/nequip/blob/main/LICENSE.
#
# This modified file is released under the same license.

import warnings
from typing import Sequence, Optional, Callable, Any

import math

import torch
import torch.nn as nn
from e3nn import o3
from e3nn.util.jit import compile_mode
from nequip.nn import GraphModuleMixin
from nequip.nn.utils import with_edge_vectors_

from nequip.data import AtomicDataDict
from nequip.nn import (
    SequentialGraphNetwork,
    ConvNetLayer,
    ApplyFactor,
)
from nequip.nn.embedding import (
    EdgeLengthNormalizer,
    BesselEdgeLengthEncoding,
    PolynomialCutoff,
    NodeTypeEmbed,
)

from modules import AuxdensityHeadForNequip

@compile_mode("script")
class SphericalHarmonicEdgeAttrs(GraphModuleMixin, torch.nn.Module):
    """Construct edge attrs as spherical harmonic projections of edge vectors.

    Parameters follow ``e3nn.o3.spherical_harmonics``.

    Args:
        irreps_edge_sh (int, str, or o3.Irreps): if int, will be treated as lmax for o3.Irreps.spherical_harmonics(lmax)
        edge_sh_normalization (str): the normalization scheme to use
        edge_sh_normalize (bool, default: True): whether to normalize the spherical harmonics
        out_field (str, default: AtomicDataDict.EDGE_ATTRS_KEY: data/irreps field
    """

    out_field: str

    def __init__(
        self,
        irreps_edge_sh: int | str | o3.Irreps,
        component_order: str = 'e3nn',
        edge_sh_normalization: str = "component",
        edge_sh_normalize: bool = True,
        irreps_in=None,
        out_field: str = AtomicDataDict.EDGE_ATTRS_KEY,
    ):
        super().__init__()
        self.out_field = out_field

        if isinstance(irreps_edge_sh, int):
            self.irreps_edge_sh = o3.Irreps.spherical_harmonics(irreps_edge_sh)
        else:
            self.irreps_edge_sh = o3.Irreps(irreps_edge_sh)
        self._init_irreps(
            irreps_in=irreps_in,
            irreps_out={out_field: self.irreps_edge_sh},
        )
        self.sh = o3.SphericalHarmonics(
            self.irreps_edge_sh, edge_sh_normalize, edge_sh_normalization
        )
        # i.e. `model_dtype`
        self._output_dtype = torch.get_default_dtype()

        assert component_order in ['e3nn', 'std'], "component_order must be 'e3nn' or 'std'"
        self.component_order = component_order

    def forward(self, data: AtomicDataDict.Type) -> AtomicDataDict.Type:
        data = with_edge_vectors_(data, with_lengths=False)
        edge_vec = data[AtomicDataDict.EDGE_VECTORS_KEY]
        if self.component_order == 'std':
            edge_vec = edge_vec[:, [1, 2, 0]]
        edge_sh = self.sh(edge_vec)
        data[self.out_field] = edge_sh.to(self._output_dtype)
        return data


class NequipArch(nn.Module):
    def __init__(
        self,
        r_max: float,
        type_names: Sequence[str],
        # convnet params
        radial_mlp_depth: Sequence[int],
        radial_mlp_width: Sequence[int],
        feature_irreps_hidden: Sequence[str | o3.Irreps],
        # irreps and dims
        irreps_edge_sh: int | str | o3.Irreps,
        type_embed_num_features: int,
        # edge length encoding
        per_edge_type_cutoff: Optional[dict[str, float | dict[str, float]]] = None,
        num_bessels: int = 8,
        bessel_trainable: bool = False,
        polynomial_cutoff_p: int = 6,
        # edge sum normalization
        avg_num_neighbors: Optional[float] = None,
        # == things that generally shouldn't be changed ==
        # convnet
        convnet_resnet: bool = False,
        convnet_nonlinearity_type: str = "gate",
        convnet_nonlinearity_scalars: dict[int, Callable] = {"e": "silu", "o": "tanh"},
        convnet_nonlinearity_gates: dict[int, Callable] = {"e": "silu", "o": "tanh"},
        task_head_specs: dict[str, Any] = {},
        auxbasis: str = "def2-universal-jfit",
    ):
        super().__init__()

        self.type_names = type_names

        # === sanity checks and warnings ===
        assert all(tn.isalnum() for tn in type_names), (
            "`type_names` must contain only alphanumeric characters"
        )

        # require every convnet layer to be specified explicitly in a list
        # infer num_layers from the list size
        assert (
            len(radial_mlp_depth) == len(radial_mlp_width) == len(feature_irreps_hidden)
        ), (
            f"radial_mlp_depth: {radial_mlp_depth}, radial_mlp_width: {radial_mlp_width}, feature_irreps_hidden: {feature_irreps_hidden} should all have the same length"
        )
        num_layers = len(radial_mlp_depth)

        if avg_num_neighbors is None:
            warnings.warn(
                "Found `avg_num_neighbors=None` -- it is recommended to set `avg_num_neighbors` for normalization and better numerics during training."
            )

        # === encode and embed features ===
        # == edge tensor embedding ==
        spharm = SphericalHarmonicEdgeAttrs(
            irreps_edge_sh=irreps_edge_sh,
            component_order="std",
        )
        # == edge scalar embedding ==
        edge_norm = EdgeLengthNormalizer(
            r_max=r_max,
            type_names=type_names,
            per_edge_type_cutoff=per_edge_type_cutoff,
            irreps_in=spharm.irreps_out,
        )
        bessel_encode = BesselEdgeLengthEncoding(
            num_bessels=num_bessels,
            trainable=bessel_trainable,
            cutoff=PolynomialCutoff(polynomial_cutoff_p),
            edge_invariant_field=AtomicDataDict.EDGE_EMBEDDING_KEY,
            irreps_in=edge_norm.irreps_out,
        )
        # for backwards compatibility of NequIP's bessel encoding
        factor = ApplyFactor(
            in_field=AtomicDataDict.EDGE_EMBEDDING_KEY,
            factor=(2 * math.pi) / (r_max * r_max),
            irreps_in=bessel_encode.irreps_out,
        )
        # == node scalar embedding ==
        type_embed = NodeTypeEmbed(
            type_names=type_names,
            num_features=type_embed_num_features,
            irreps_in=factor.irreps_out,
        )
        modules = {
            "spharm": spharm,
            "edge_norm": edge_norm,
            "bessel_encode": bessel_encode,
            "factor": factor,
            "type_embed": type_embed,
        }
        prev_irreps_out = type_embed.irreps_out

        # === convnet layers ===
        for layer_i in range(num_layers):
            current_convnet = ConvNetLayer(
                irreps_in=prev_irreps_out,
                feature_irreps_hidden=feature_irreps_hidden[layer_i],
                convolution_kwargs={
                    "radial_mlp_depth": radial_mlp_depth[layer_i],
                    "radial_mlp_width": radial_mlp_width[layer_i],
                    "avg_num_neighbors": avg_num_neighbors,
                    # to ensure isolated atom limit
                    "use_sc": layer_i != 0,
                },
                resnet=(layer_i != 0) and convnet_resnet,
                nonlinearity_type=convnet_nonlinearity_type,
                nonlinearity_scalars=convnet_nonlinearity_scalars,
                nonlinearity_gates=convnet_nonlinearity_gates,
            )
            prev_irreps_out = current_convnet.irreps_out
            modules.update({f"layer{layer_i}_convnet": current_convnet})

        # === assemble in SequentialGraphNetwork ===
        self.backbone = SequentialGraphNetwork(modules)

        # === readout ===
        self.backbone_irreps_out = prev_irreps_out
        self.task_head = SequentialGraphNetwork(
            {
                "auxdensity_atom_readout": AuxdensityHeadForNequip(
                    type_names=self.type_names,
                    auxbasis=auxbasis,
                    field=AtomicDataDict.NODE_FEATURES_KEY,
                    out_field="output:auxdensity",
                    biases=True,
                    irreps_in=self.backbone_irreps_out,
                ),
            }
        )

    def convert_inputs(self, inputs):
        ret = inputs.copy()
        ret.update(
            {
                AtomicDataDict.ATOM_TYPE_KEY: inputs["z"],
                AtomicDataDict.POSITIONS_KEY: inputs["pos"],
                AtomicDataDict.EDGE_INDEX_KEY: inputs["edge_index"],
            }
        )
        return ret

    def forward(self, data):
        data = self.convert_inputs(data)
        data = self.backbone(data)
        data = self.task_head(data)
        return data


def nequip_simple_builder(
    num_layers: int = 4,
    l_max: int = 1,
    parity: bool = True,
    num_features: int = 32,
    radial_mlp_depth: int = 2,
    radial_mlp_width: int = 64,
    **kwargs,
) -> nn.Module:
    irreps_edge_sh = repr(
        o3.Irreps.spherical_harmonics(lmax=l_max, p=-1 if parity else 1)
    )
    feature_irreps_hidden = repr(
        o3.Irreps(
            [
                (num_features, (l, p))
                for p in ((1, -1) if parity else (1,))
                for l in range(l_max + 1)
            ]
        )
    )
    feature_irreps_hidden_list = [feature_irreps_hidden] * (num_layers - 1)
    radial_mlp_depth_list = [radial_mlp_depth] * num_layers
    radial_mlp_width_list = [radial_mlp_width] * num_layers

    feature_irreps_hidden_list += [feature_irreps_hidden]

    model = NequipArch(
        irreps_edge_sh=irreps_edge_sh,
        type_embed_num_features=num_features,
        feature_irreps_hidden=feature_irreps_hidden_list,
        radial_mlp_depth=radial_mlp_depth_list,
        radial_mlp_width=radial_mlp_width_list,
        **kwargs,
    )
    return model


if __name__ == "__main__":
    model = nequip_simple_builder(r_max=5.0, type_names=["H", "C", "N", "O", "F", "P", "S"])
    from dataset import SCFBenchDataset
    dataset = SCFBenchDataset("dataset/main", parts_to_load=["base", "auxdensity.denfit"])
    print(model(dataset[0])['output:auxdensity'])