Skip to content

Commit 5a32c49

Browse files
authored
Merge pull request #1803 from amcadmus/master
Merge devel into master
2 parents 03c8742 + e8a57ca commit 5a32c49

File tree

107 files changed

+6552
-246
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+6552
-246
lines changed

.github/workflows/build_wheel.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ jobs:
2828
- name: Build wheels
2929
env:
3030
CIBW_BUILD: "cp36-* cp37-* cp38-* cp39-* cp310-*"
31-
CIBW_MANYLINUX_X86_64_IMAGE: ghcr.io/deepmodeling/manylinux2014_x86_64_tensorflow
31+
CIBW_MANYLINUX_X86_64_IMAGE: ghcr.io/deepmodeling/manylinux_2_24_x86_64_tensorflow
3232
CIBW_BEFORE_BUILD: pip install tensorflow
3333
CIBW_SKIP: "*-win32 *-manylinux_i686 *-musllinux*"
3434
run: |

.github/workflows/lint_python.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ jobs:
2121
run: pip install -r requirements.txt
2222
- uses: marian-code/[email protected]
2323
with:
24-
python-root-list: "./deepmd/*.py ./deepmd/*/*.py ./source/train/*.py ./source/tests/*.py ./source/op/*.py"
24+
python-root-list: "./deepmd/*.py ./deepmd/*/*.py ./deepmd/*/*/*.py ./source/train/*.py ./source/tests/*.py ./source/op/*.py"
2525
use-black: true
2626
use-isort: true
2727
use-mypy: true

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ A full [document](doc/train/train-input-auto.rst) on options in the training inp
124124
- [Run path-integral MD with i-PI](doc/third-party/ipi.md)
125125
- [Run MD with GROMACS](doc/third-party/gromacs.md)
126126
- [Interfaces out of DeePMD-kit](doc/third-party/out-of-deepmd-kit.md)
127+
- [Use NVNMD](doc/nvnmd/index.md)
127128

128129
# Code structure
129130

deepmd/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import importlib_metadata as metadata
77
import deepmd.utils.network as network
88

9-
from . import cluster, descriptor, fit, loss, utils
9+
from . import cluster, descriptor, fit, loss, utils, nvnmd
1010
from .env import set_mkl
1111
from .infer import DeepEval, DeepPotential
1212
from .infer.data_modifier import DipoleChargeModifier
@@ -32,4 +32,5 @@
3232
"DeepEval",
3333
"DeepPotential",
3434
"DipoleChargeModifier",
35+
"nvnmd",
3536
]

deepmd/common.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from typing import Literal # python >3.6
3535
except ImportError:
3636
from typing_extensions import Literal # type: ignore
37-
_ACTIVATION = Literal["relu", "relu6", "softplus", "sigmoid", "tanh", "gelu"]
37+
_ACTIVATION = Literal["relu", "relu6", "softplus", "sigmoid", "tanh", "gelu", "gelu_tf"]
3838
_PRECISION = Literal["default", "float16", "float32", "float64"]
3939

4040
# define constants
@@ -49,7 +49,7 @@
4949
def gelu(x: tf.Tensor) -> tf.Tensor:
5050
"""Gaussian Error Linear Unit.
5151
52-
This is a smoother version of the RELU.
52+
This is a smoother version of the RELU, implemented by custom operator.
5353
5454
Parameters
5555
----------
@@ -58,7 +58,31 @@ def gelu(x: tf.Tensor) -> tf.Tensor:
5858
5959
Returns
6060
-------
61-
`x` with the GELU activation applied
61+
tf.Tensor
62+
`x` with the GELU activation applied
63+
64+
References
65+
----------
66+
Original paper
67+
https://arxiv.org/abs/1606.08415
68+
"""
69+
return op_module.gelu(x)
70+
71+
72+
def gelu_tf(x: tf.Tensor) -> tf.Tensor:
73+
"""Gaussian Error Linear Unit.
74+
75+
This is a smoother version of the RELU, implemented by TF.
76+
77+
Parameters
78+
----------
79+
x : tf.Tensor
80+
float Tensor to perform activation
81+
82+
Returns
83+
-------
84+
tf.Tensor
85+
`x` with the GELU activation applied
6286
6387
References
6488
----------
@@ -69,10 +93,10 @@ def gelu_wrapper(x):
6993
try:
7094
return tensorflow.nn.gelu(x, approximate=True)
7195
except AttributeError:
96+
warnings.warn("TensorFlow does not provide an implementation of gelu, please upgrade your TensorFlow version. Fallback to the custom gelu operator.")
7297
return op_module.gelu(x)
7398
return (lambda x: gelu_wrapper(x))(x)
7499

75-
76100
# TODO this is not a good way to do things. This is some global variable to which
77101
# TODO anyone can write and there is no good way to keep track of the changes
78102
data_requirement = {}
@@ -84,6 +108,7 @@ def gelu_wrapper(x):
84108
"sigmoid": tf.sigmoid,
85109
"tanh": tf.nn.tanh,
86110
"gelu": gelu,
111+
"gelu_tf": gelu_tf,
87112
}
88113

89114

deepmd/descriptor/se_a.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
from .descriptor import Descriptor
1818
from .se import DescrptSe
1919

20+
from deepmd.nvnmd.descriptor.se_a import descrpt2r4, build_davg_dstd, build_op_descriptor, filter_lower_R42GR, filter_GR2D
21+
from deepmd.nvnmd.utils.config import nvnmd_cfg
22+
2023
@Descriptor.register("se_e2_a")
2124
@Descriptor.register("se_a")
2225
class DescrptSeA (DescrptSe):
@@ -412,6 +415,7 @@ def build (self,
412415
"""
413416
davg = self.davg
414417
dstd = self.dstd
418+
if nvnmd_cfg.enable and nvnmd_cfg.restore_descriptor: davg, dstd = build_davg_dstd()
415419
with tf.variable_scope('descrpt_attr' + suffix, reuse = reuse) :
416420
if davg is None:
417421
davg = np.zeros([self.ntypes, self.ndescrpt])
@@ -448,8 +452,9 @@ def build (self,
448452
box = tf.reshape (box_, [-1, 9])
449453
atype = tf.reshape (atype_, [-1, natoms[1]])
450454

455+
op_descriptor = build_op_descriptor() if nvnmd_cfg.enable else op_module.prod_env_mat_a
451456
self.descrpt, self.descrpt_deriv, self.rij, self.nlist \
452-
= op_module.prod_env_mat_a (coord,
457+
= op_descriptor (coord,
453458
atype,
454459
natoms,
455460
box,
@@ -576,6 +581,8 @@ def _pass_filter(self,
576581
inputs_i = inputs
577582
inputs_i = tf.reshape(inputs_i, [-1, self.ndescrpt])
578583
type_i = -1
584+
if nvnmd_cfg.enable and nvnmd_cfg.quantize_descriptor:
585+
inputs_i = descrpt2r4(inputs_i, natoms)
579586
layer, qmat = self._filter(inputs_i, type_i, name='filter_type_all'+suffix, natoms=natoms, reuse=reuse, trainable = trainable, activation_fn = self.filter_activation_fn, type_embedding=type_embedding)
580587
layer = tf.reshape(layer, [tf.shape(inputs)[0], natoms[0], self.get_dim_out()])
581588
qmat = tf.reshape(qmat, [tf.shape(inputs)[0], natoms[0], self.get_dim_rot_mat_1() * 3])
@@ -717,6 +724,14 @@ def _filter_lower(
717724
if self.compress:
718725
raise RuntimeError('compression of type embedded descriptor is not supported at the moment')
719726
# natom x 4 x outputs_size
727+
if nvnmd_cfg.enable:
728+
return filter_lower_R42GR(
729+
type_i, type_input, inputs_i, is_exclude,
730+
activation_fn, bavg, stddev, trainable,
731+
suffix, self.seed, self.seed_shift, self.uniform_seed,
732+
self.filter_neuron, self.filter_precision, self.filter_resnet_dt,
733+
self.embedding_net_variables
734+
)
720735
if self.compress and (not is_exclude):
721736
if self.type_one_side:
722737
net = 'filter_-1_net_' + str(type_i)
@@ -825,6 +840,7 @@ def _filter(
825840
stddev = stddev,
826841
bavg = bavg,
827842
trainable = trainable)
843+
if nvnmd_cfg.enable: return filter_GR2D(xyz_scatter_1)
828844
# natom x nei x outputs_size
829845
# xyz_scatter = tf.concat(xyz_scatter_total, axis=1)
830846
# natom x nei x 4

deepmd/entrypoints/freeze.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
from typing import List, Optional
2121

22+
from deepmd.nvnmd.entrypoints.freeze import save_weight
23+
2224
__all__ = ["freeze"]
2325

2426
log = logging.getLogger(__name__)
@@ -160,7 +162,7 @@ def _make_node_names(model_type: str, modifier_type: Optional[str] = None) -> Li
160162

161163

162164
def freeze(
163-
*, checkpoint_folder: str, output: str, node_names: Optional[str] = None, **kwargs
165+
*, checkpoint_folder: str, output: str, node_names: Optional[str] = None, nvnmd_weight: Optional[str] = None, **kwargs
164166
):
165167
"""Freeze the graph in supplied folder.
166168
@@ -237,6 +239,9 @@ def freeze(
237239
output_node_list = node_names.split(",")
238240
log.info(f"The following nodes will be frozen: {output_node_list}")
239241

242+
if nvnmd_weight is not None:
243+
save_weight(sess, nvnmd_weight) # nvnmd
244+
240245
# We use a built-in TF helper to export variables to constants
241246
output_graph_def = tf.graph_util.convert_variables_to_constants(
242247
sess, # The session is used to retrieve the weights

deepmd/entrypoints/main.py

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
)
2121
from deepmd.loggers import set_log_handles
2222

23+
from deepmd.nvnmd.entrypoints.train import train_nvnmd
24+
2325
__all__ = ["main", "parse_args", "get_ll", "main_parser"]
2426

2527

@@ -204,6 +206,13 @@ def main_parser() -> argparse.ArgumentParser:
204206
default=None,
205207
help="the frozen nodes, if not set, determined from the model type",
206208
)
209+
parser_frz.add_argument(
210+
"-w",
211+
"--nvnmd-weight",
212+
type=str,
213+
default=None,
214+
help="the name of weight file (.npy), if set, save the model's weight into the file",
215+
)
207216

208217
# * test script ********************************************************************
209218
parser_tst = subparsers.add_parser(
@@ -436,9 +445,28 @@ def main_parser() -> argparse.ArgumentParser:
436445
required=True,
437446
help="type map",
438447
)
439-
448+
440449
# --version
441450
parser.add_argument('--version', action='version', version='DeePMD-kit v%s' % __version__)
451+
452+
# * train nvnmd script ******************************************************************
453+
parser_train_nvnmd = subparsers.add_parser(
454+
"train-nvnmd",
455+
parents=[parser_log],
456+
help="train nvnmd model",
457+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
458+
)
459+
parser_train_nvnmd.add_argument(
460+
"INPUT", help="the input parameter file in json format"
461+
)
462+
parser_train_nvnmd.add_argument(
463+
"-s",
464+
"--step",
465+
default="s1",
466+
type=str,
467+
choices=['s1', 's2'],
468+
help="steps to train model of NVNMD: s1 (train CNN), s2 (train QNN)"
469+
)
442470
return parser
443471

444472

@@ -504,6 +532,8 @@ def main():
504532
convert(**dict_args)
505533
elif args.command == "neighbor-stat":
506534
neighbor_stat(**dict_args)
535+
elif args.command == "train-nvnmd": # nvnmd
536+
train_nvnmd(**dict_args)
507537
elif args.command is None:
508538
pass
509539
else:

deepmd/env.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,13 +281,21 @@ def get_module(module_name: str) -> "ModuleType":
281281
TF_VERSION,
282282
tf_py_version,
283283
)) from e
284-
raise RuntimeError(
284+
error_message = (
285285
"This deepmd-kit package is inconsitent with TensorFlow "
286286
"Runtime, thus an error is raised when loading %s. "
287287
"You need to rebuild deepmd-kit against this TensorFlow "
288288
"runtime." % (
289289
module_name,
290-
)) from e
290+
)
291+
)
292+
if TF_CXX11_ABI_FLAG == 1:
293+
# #1791
294+
error_message += (
295+
"\nWARNING: devtoolset on RHEL6 and RHEL7 does not support _GLIBCXX_USE_CXX11_ABI=1. "
296+
"See https://bugzilla.redhat.com/show_bug.cgi?id=1546704"
297+
)
298+
raise RuntimeError(error_message) from e
291299
return module
292300

293301

deepmd/fit/ener.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,18 @@
55

66
from deepmd.env import tf
77
from deepmd.common import add_data_requirement, get_activation_func, get_precision, cast_precision
8-
from deepmd.utils.network import one_layer, one_layer_rand_seed_shift
8+
from deepmd.utils.network import one_layer_rand_seed_shift
9+
from deepmd.utils.network import one_layer as one_layer_deepmd
910
from deepmd.utils.type_embed import embed_atom_type
1011
from deepmd.utils.graph import get_fitting_net_variables_from_graph_def, load_graph_def, get_tensor_by_name_from_graph
1112
from deepmd.fit.fitting import Fitting
1213

1314
from deepmd.env import global_cvt_2_tf_float
1415
from deepmd.env import GLOBAL_TF_FLOAT_PRECISION, TF_VERSION
1516

17+
from deepmd.nvnmd.utils.config import nvnmd_cfg
18+
from deepmd.nvnmd.fit.ener import one_layer_nvnmd
19+
1620
class EnerFitting (Fitting):
1721
r"""Fitting the energy of the system. The force and the virial can also be trained.
1822
@@ -291,8 +295,12 @@ def _build_lower(
291295
ext_aparam = tf.cast(ext_aparam,self.fitting_precision)
292296
layer = tf.concat([layer, ext_aparam], axis = 1)
293297

298+
if nvnmd_cfg.enable:
299+
one_layer = one_layer_nvnmd
300+
else:
301+
one_layer = one_layer_deepmd
294302
for ii in range(0,len(self.n_neuron)) :
295-
if ii >= 1 and self.n_neuron[ii] == self.n_neuron[ii-1] :
303+
if ii >= 1 and self.n_neuron[ii] == self.n_neuron[ii-1] and (not nvnmd_cfg.enable):
296304
layer+= one_layer(
297305
layer,
298306
self.n_neuron[ii],

0 commit comments

Comments
 (0)