forked from aimat-lab/gcnn_keras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_make.py
354 lines (308 loc) · 17.8 KB
/
_make.py
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import tensorflow as tf
from ._dimenet_conv import DimNetInteractionPPBlock, DimNetOutputBlock, EmbeddingDimeBlock, SphericalBasisLayer
from kgcnn.layers.gather import GatherNodes
from kgcnn.layers.geom import NodeDistanceEuclidean, EdgeAngle, BesselBasisLayer, NodePosition, ShiftPeriodicLattice
from kgcnn.layers.modules import Dense, LazyConcatenate, LazyAdd, LazySubtract
from kgcnn.layers.pooling import PoolingNodes
from kgcnn.model.utils import update_model_kwargs
from kgcnn.layers.mlp import MLP
ks = tf.keras
# Keep track of model version from commit date in literature.
# To be updated if model is changed in a significant way.
__model_version__ = "2022.11.25"
# Implementation of DimeNet++ in `tf.keras` from paper:
# Fast and Uncertainty-Aware Directional Message Passing for Non-Equilibrium Molecules
# Johannes Klicpera, Shankari Giri, Johannes T. Margraf, Stephan Günnemann
# https://arxiv.org/abs/2011.14115
# Original code: https://github.com/gasteigerjo/dimenet
model_default = {
"name": "DimeNetPP",
"inputs": [{"shape": [None], "name": "node_attributes", "dtype": "float32", "ragged": True},
{"shape": [None, 3], "name": "node_coordinates", "dtype": "float32", "ragged": True},
{"shape": [None, 2], "name": "edge_indices", "dtype": "int64", "ragged": True},
{"shape": [None, 2], "name": "angle_indices", "dtype": "int64", "ragged": True}],
"input_embedding": {"node": {"input_dim": 95, "output_dim": 128,
"embeddings_initializer": {"class_name": "RandomUniform",
"config": {"minval": -1.7320508075688772,
"maxval": 1.7320508075688772}}}},
"emb_size": 128, "out_emb_size": 256, "int_emb_size": 64, "basis_emb_size": 8,
"num_blocks": 4, "num_spherical": 7, "num_radial": 6,
"cutoff": 5.0, "envelope_exponent": 5,
"num_before_skip": 1, "num_after_skip": 2, "num_dense_output": 3,
"num_targets": 64, "extensive": True, "output_init": "zeros",
"activation": "swish", "verbose": 10,
"output_embedding": "graph",
"use_output_mlp": True,
"output_mlp": {"use_bias": [True, False],
"units": [64, 12], "activation": ["swish", "linear"]}
}
@update_model_kwargs(model_default)
def make_model(inputs: list = None,
input_embedding: dict = None,
emb_size: int = None,
out_emb_size: int = None,
int_emb_size: int = None,
basis_emb_size: int = None,
num_blocks: int = None,
num_spherical: int = None,
num_radial: int = None,
cutoff: float = None,
envelope_exponent: int = None,
num_before_skip: int = None,
num_after_skip: int = None,
num_dense_output: int = None,
num_targets: int = None,
activation: str = None,
extensive: bool = None,
output_init: str = None,
verbose: int = None,
name: str = None,
output_embedding: str = None,
use_output_mlp: bool = None,
output_mlp: dict = None
):
"""Make `DimeNetPP <https://arxiv.org/abs/2011.14115>`_ graph network via functional API.
Default parameters can be found in :obj:`kgcnn.literature.DimeNetPP.model_default`.
.. note::
DimeNetPP does require a large amount of memory for this implementation, which increase quickly with
the number of connections in a batch.
Inputs:
list: `[node_attributes, node_coordinates, bond_indices, angle_indices]`
- node_attributes (tf.RaggedTensor): Node attributes of shape `(batch, None, F)` or `(batch, None)`
using an embedding layer.
- node_coordinates (tf.RaggedTensor): Atomic coordinates of shape `(batch, None, 3)`.
- bond_indices (tf.RaggedTensor): Index list for edges or bonds of shape `(batch, None, 2)`.
- angle_indices (tf.RaggedTensor): Index list of angles referring to bonds of shape `(batch, None, 2)`.
Outputs:
tf.Tensor: Graph embeddings of shape `(batch, L)` if :obj:`output_embedding="graph"`.
Args:
inputs (list): List of dictionaries unpacked in :obj:`tf.keras.layers.Input`. Order must match model definition.
input_embedding (dict): Dictionary of embedding arguments for nodes etc. unpacked in :obj:`Embedding` layers.
emb_size (int): Overall embedding size used for the messages.
out_emb_size (int): Embedding size for output of :obj:`DimNetOutputBlock`.
int_emb_size (int): Embedding size used for interaction triplets.
basis_emb_size (int): Embedding size used inside the basis transformation.
num_blocks (int): Number of graph embedding blocks or depth of the network.
num_spherical (int): Number of spherical components in :obj:`SphericalBasisLayer`.
num_radial (int): Number of radial components in basis layer.
cutoff (float): Distance cutoff for basis layer.
envelope_exponent (int): Exponent in envelope function for basis layer.
num_before_skip (int): Number of residual layers in interaction block before skip connection
num_after_skip (int): Number of residual layers in interaction block after skip connection
num_dense_output (int): Number of dense units in output :obj:`DimNetOutputBlock`.
num_targets (int): Number of targets or output embedding dimension of the model.
activation (str, dict): Activation to use.
extensive (bool): Graph output for extensive target to apply sum for pooling or mean otherwise.
output_init (str, dict): Output initializer for kernel.
verbose (int): Level of verbosity.
name (str): Name of the model.
output_embedding (str): Main embedding task for graph network. Either "node", "edge" or "graph".
use_output_mlp (bool): Whether to use the final output MLP. Possibility to skip final :obj:`MLP`.
output_mlp (dict): Dictionary of layer arguments unpacked in the final classification :obj:`MLP` layer block.
Defines number of model outputs and activation. Note that DimeNetPP originally defines the output dimension
via `num_targets`. But this can be set to `out_emb_size` and the `output_mlp` be used for more
specific control.
Returns:
:obj:`tf.keras.models.Model`
"""
# Make input
node_input = ks.layers.Input(**inputs[0])
xyz_input = ks.layers.Input(**inputs[1])
bond_index_input = ks.layers.Input(**inputs[2])
angle_index_input = ks.layers.Input(**inputs[3])
# Atom embedding
# n = generate_node_embedding(node_input, input_node_shape, input_embedding["nodes"])
if len(inputs[0]["shape"]) == 1:
n = EmbeddingDimeBlock(**input_embedding["node"])(node_input)
else:
n = node_input
x = xyz_input
edi = bond_index_input
adi = angle_index_input
# Calculate distances
pos1, pos2 = NodePosition()([x, edi])
d = NodeDistanceEuclidean()([pos1, pos2])
rbf = BesselBasisLayer(num_radial=num_radial, cutoff=cutoff, envelope_exponent=envelope_exponent)(d)
# Calculate angles
v12 = LazySubtract()([pos1, pos2])
a = EdgeAngle()([v12, adi])
sbf = SphericalBasisLayer(num_spherical=num_spherical, num_radial=num_radial, cutoff=cutoff,
envelope_exponent=envelope_exponent)([d, a, adi])
# Embedding block
rbf_emb = Dense(emb_size, use_bias=True, activation=activation,
kernel_initializer="kgcnn>glorot_orthogonal")(rbf)
n_pairs = GatherNodes()([n, edi])
x = LazyConcatenate(axis=-1)([n_pairs, rbf_emb])
x = Dense(emb_size, use_bias=True, activation=activation, kernel_initializer="kgcnn>glorot_orthogonal")(x)
ps = DimNetOutputBlock(emb_size, out_emb_size, num_dense_output, num_targets=num_targets,
output_kernel_initializer=output_init)([n, x, rbf, edi])
# Interaction blocks
add_xp = LazyAdd()
for i in range(num_blocks):
x = DimNetInteractionPPBlock(emb_size, int_emb_size, basis_emb_size, num_before_skip, num_after_skip)(
[x, rbf, sbf, adi])
p_update = DimNetOutputBlock(emb_size, out_emb_size, num_dense_output, num_targets=num_targets,
output_kernel_initializer=output_init)([n, x, rbf, edi])
ps = add_xp([ps, p_update])
if extensive:
out = PoolingNodes(pooling_method="sum")(ps)
else:
out = PoolingNodes(pooling_method="mean")(ps)
if use_output_mlp:
out = MLP(**output_mlp)(out)
if output_embedding != "graph":
raise ValueError("Unsupported output embedding for mode `DimeNetPP`.")
model = ks.models.Model(inputs=[node_input, xyz_input, bond_index_input, angle_index_input],
outputs=out)
model.__kgcnn_model_version__ = __model_version__
return model
model_crystal_default = {
"name": "DimeNetPP",
"inputs": [{"shape": [None], "name": "node_attributes", "dtype": "float32", "ragged": True},
{"shape": [None, 3], "name": "node_coordinates", "dtype": "float32", "ragged": True},
{"shape": [None, 2], "name": "edge_indices", "dtype": "int64", "ragged": True},
{"shape": [None, 2], "name": "angle_indices", "dtype": "int64", "ragged": True},
{'shape': (None, 3), 'name': "edge_image", 'dtype': 'int64', 'ragged': True},
{'shape': (3, 3), 'name': "graph_lattice", 'dtype': 'float32', 'ragged': False}
],
"input_embedding": {"node": {"input_dim": 95, "output_dim": 128,
"embeddings_initializer": {"class_name": "RandomUniform",
"config": {"minval": -1.7320508075688772,
"maxval": 1.7320508075688772}}}},
"emb_size": 128, "out_emb_size": 256, "int_emb_size": 64, "basis_emb_size": 8,
"num_blocks": 4, "num_spherical": 7, "num_radial": 6,
"cutoff": 5.0, "envelope_exponent": 5,
"num_before_skip": 1, "num_after_skip": 2, "num_dense_output": 3,
"num_targets": 64, "extensive": True, "output_init": "zeros",
"activation": "swish", "verbose": 10,
"output_embedding": "graph",
"use_output_mlp": True,
"output_mlp": {"use_bias": [True, False],
"units": [64, 12], "activation": ["swish", "linear"]}
}
@update_model_kwargs(model_crystal_default)
def make_crystal_model(inputs: list = None,
input_embedding: dict = None,
emb_size: int = None,
out_emb_size: int = None,
int_emb_size: int = None,
basis_emb_size: int = None,
num_blocks: int = None,
num_spherical: int = None,
num_radial: int = None,
cutoff: float = None,
envelope_exponent: int = None,
num_before_skip: int = None,
num_after_skip: int = None,
num_dense_output: int = None,
num_targets: int = None,
activation: str = None,
extensive: bool = None,
output_init: str = None,
verbose: int = None,
name: str = None,
output_embedding: str = None,
use_output_mlp: bool = None,
output_mlp: dict = None
):
"""Make `DimeNetPP <https://arxiv.org/abs/2011.14115>`_ graph network via functional API.
Default parameters can be found in :obj:`kgcnn.literature.DimeNetPP.model_crystal_default`.
.. note::
DimeNetPP does require a large amount of memory for this implementation, which increase quickly with
the number of connections in a batch.
Inputs:
list: `[node_attributes, node_coordinates, bond_indices, angle_indices, edge_image, lattice]`
- node_attributes (tf.RaggedTensor): Node attributes of shape `(batch, None, F)` or `(batch, None)`
using an embedding layer.
- node_coordinates (tf.RaggedTensor): Atomic coordinates of shape `(batch, None, 3)`.
- bond_indices (tf.RaggedTensor): Index list for edges or bonds of shape `(batch, None, 2)`.
- angle_indices (tf.RaggedTensor): Index list of angles referring to bonds of shape `(batch, None, 2)`.
- lattice (tf.Tensor): Lattice matrix of the periodic structure of shape `(batch, 3, 3)`.
- edge_image (tf.RaggedTensor): Indices of the periodic image the sending node is located. The indices
of and edge are :math:`(i, j)` with :math:`j` being the sending node.
Outputs:
tf.Tensor: Graph embeddings of shape `(batch, L)` if :obj:`output_embedding="graph"`.
Args:
inputs (list): List of dictionaries unpacked in :obj:`tf.keras.layers.Input`. Order must match model definition.
input_embedding (dict): Dictionary of embedding arguments for nodes etc. unpacked in :obj:`Embedding` layers.
emb_size (int): Overall embedding size used for the messages.
out_emb_size (int): Embedding size for output of :obj:`DimNetOutputBlock`.
int_emb_size (int): Embedding size used for interaction triplets.
basis_emb_size (int): Embedding size used inside the basis transformation.
num_blocks (int): Number of graph embedding blocks or depth of the network.
num_spherical (int): Number of spherical components in :obj:`SphericalBasisLayer`.
num_radial (int): Number of radial components in basis layer.
cutoff (float): Distance cutoff for basis layer.
envelope_exponent (int): Exponent in envelope function for basis layer.
num_before_skip (int): Number of residual layers in interaction block before skip connection
num_after_skip (int): Number of residual layers in interaction block after skip connection
num_dense_output (int): Number of dense units in output :obj:`DimNetOutputBlock`.
num_targets (int): Number of targets or output embedding dimension of the model.
activation (str, dict): Activation to use.
extensive (bool): Graph output for extensive target to apply sum for pooling or mean otherwise.
output_init (str, dict): Output initializer for kernel.
verbose (int): Level of verbosity.
name (str): Name of the model.
output_embedding (str): Main embedding task for graph network. Either "node", "edge" or "graph".
use_output_mlp (bool): Whether to use the final output MLP. Possibility to skip final :obj:`MLP`.
output_mlp (dict): Dictionary of layer arguments unpacked in the final classification :obj:`MLP` layer block.
Defines number of model outputs and activation. Note that DimeNetPP originally defines the output dimension
via `num_targets`. But this can be set to `out_emb_size` and the `output_mlp` be used for more
specific control.
Returns:
:obj:`tf.keras.models.Model`
"""
# Make input
node_input = ks.layers.Input(**inputs[0])
xyz_input = ks.layers.Input(**inputs[1])
bond_index_input = ks.layers.Input(**inputs[2])
angle_index_input = ks.layers.Input(**inputs[3])
edge_image = ks.layers.Input(**inputs[4])
lattice = ks.layers.Input(**inputs[5])
# Atom embedding
# n = generate_node_embedding(node_input, input_node_shape, input_embedding["nodes"])
if len(inputs[0]["shape"]) == 1:
n = EmbeddingDimeBlock(**input_embedding["node"])(node_input)
else:
n = node_input
x = xyz_input
edi = bond_index_input
adi = angle_index_input
# Calculate distances
pos1, pos2 = NodePosition()([x, edi])
pos2 = ShiftPeriodicLattice()([pos2, edge_image, lattice])
d = NodeDistanceEuclidean()([pos1, pos2])
rbf = BesselBasisLayer(num_radial=num_radial, cutoff=cutoff, envelope_exponent=envelope_exponent)(d)
# Calculate angles
v12 = LazySubtract()([pos1, pos2])
a = EdgeAngle()([v12, adi])
sbf = SphericalBasisLayer(num_spherical=num_spherical, num_radial=num_radial, cutoff=cutoff,
envelope_exponent=envelope_exponent)([d, a, adi])
# Embedding block
rbf_emb = Dense(emb_size, use_bias=True, activation=activation,
kernel_initializer="kgcnn>glorot_orthogonal")(rbf)
n_pairs = GatherNodes()([n, edi])
x = LazyConcatenate(axis=-1)([n_pairs, rbf_emb])
x = Dense(emb_size, use_bias=True, activation=activation, kernel_initializer="kgcnn>glorot_orthogonal")(x)
ps = DimNetOutputBlock(emb_size, out_emb_size, num_dense_output, num_targets=num_targets,
output_kernel_initializer=output_init)([n, x, rbf, edi])
# Interaction blocks
add_xp = LazyAdd()
for i in range(num_blocks):
x = DimNetInteractionPPBlock(emb_size, int_emb_size, basis_emb_size, num_before_skip, num_after_skip)(
[x, rbf, sbf, adi])
p_update = DimNetOutputBlock(emb_size, out_emb_size, num_dense_output, num_targets=num_targets,
output_kernel_initializer=output_init)([n, x, rbf, edi])
ps = add_xp([ps, p_update])
if extensive:
out = PoolingNodes(pooling_method="sum")(ps)
else:
out = PoolingNodes(pooling_method="mean")(ps)
if use_output_mlp:
out = MLP(**output_mlp)(out)
if output_embedding != "graph":
raise ValueError("Unsupported output embedding for mode `DimeNetPP`.")
model = ks.models.Model(inputs=[node_input, xyz_input, bond_index_input, angle_index_input, edge_image, lattice],
outputs=out)
model.__kgcnn_model_version__ = __model_version__
return model