DeePMD-kit’s documentation
DeePMD-kit is a package written in Python/C++, designed to minimize the effort required to build deep learning-based models of interatomic potential energy and force field and to perform molecular dynamics (MD). This brings new hopes to addressing the accuracy-versus-efficiency dilemma in molecular simulations. Applications of DeePMD-kit span from finite molecules to extended systems and from metallic systems to chemically bonded systems.
Important
The project DeePMD-kit is licensed under GNU LGPLv3.0. If you use this code in any future publications, please cite the following publications for general purpose:
Han Wang, Linfeng Zhang, Jiequn Han, and Weinan E. “DeePMD-kit: A deep learning package for many-body potential energy representation and molecular dynamics.” Computer Physics Communications 228 (2018): 178-184.
Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang. “DeePMD-kit v2: A software package for Deep Potential models.” J. Chem. Phys., 159, 054801 (2023).
In addition, please follow this page to cite the methods you used.
Getting Started
In this text, we will call the deep neural network that is used to represent the interatomic interactions (Deep Potential) the model. The typical procedure of using DeePMD-kit is
Easy install
There are various easy methods to install DeePMD-kit. Choose one that you prefer. If you want to build by yourself, jump to the next two sections.
After your easy installation, DeePMD-kit (dp) and LAMMPS (lmp) will be available to execute. You can try dp -h and lmp -h to see the help. mpirun is also available considering you may want to train models or run LAMMPS in parallel.
Note
Note: The off-line packages and conda packages require the GNU C Library 2.17 or above. The GPU version requires compatible NVIDIA driver to be installed in advance. It is possible to force conda to override detection when installation, but these requirements are still necessary during runtime. You can refer to DeepModeling conda FAQ for more information.
Install off-line packages
Both CPU and GPU version offline packages are available in the Releases page.
Some packages are splited into two files due to size limit of GitHub. One may merge them into one after downloading:
cat deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh.0 deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh.1 > deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh
One may enable the environment using
conda activate /path/to/deepmd-kit
Install with conda
DeePMD-kit is available with conda. Install Anaconda, Miniconda, or miniforge first. You can refer to DeepModeling conda FAQ for how to setup a conda environment.
conda-forge channel
DeePMD-kit is available on the conda-forge channel:
conda create -n deepmd deepmd-kit lammps horovod -c conda-forge
The supported platforms include Linux x86-64, macOS x86-64, and macOS arm64. Read conda-forge FAQ to learn how to install CUDA-enabled packages.
Official channel
Danger
Deprecated since version 3.0.0: The official channel will be deprecated since 3.0.0. Old packages will still be available at https://conda.deepmodeling.com. Maintainers will build packages in the conda-forge organization together with other conda-forge members.
One may create an environment that contains the CPU version of DeePMD-kit and LAMMPS:
conda create -n deepmd deepmd-kit=*=*cpu libdeepmd=*=*cpu lammps -c https://conda.deepmodeling.com -c defaults
Or one may want to create a GPU environment containing CUDA Toolkit:
conda create -n deepmd deepmd-kit=*=*gpu libdeepmd=*=*gpu lammps cudatoolkit=11.6 horovod -c https://conda.deepmodeling.com -c defaults
One could change the CUDA Toolkit version from 10.2 or 11.6.
One may specify the DeePMD-kit version such as 2.2.9 using
conda create -n deepmd deepmd-kit=2.2.9=*cpu libdeepmd=2.2.9=*cpu lammps horovod -c https://conda.deepmodeling.com -c defaults
One may enable the environment using
conda activate deepmd
Install with docker
A docker for installing the DeePMD-kit is available here.
To pull the CPU version:
docker pull ghcr.io/deepmodeling/deepmd-kit:2.1.1_cpu
To pull the GPU version:
docker pull ghcr.io/deepmodeling/deepmd-kit:2.1.1_cuda11.6_gpu
To pull the ROCm version:
docker pull deepmodeling/dpmdkit-rocm:dp2.0.3-rocm4.5.2-tf2.6-lmp29Sep2021
Install Python interface with pip
If you have no existing TensorFlow installed, you can use pip to install the pre-built package of the Python interface with CUDA 12 supported:
pip install deepmd-kit[gpu,cu12]
cu12 is required only when CUDA Toolkit and cuDNN were not installed.
To install the package built against CUDA 11.8, use
pip install deepmd-kit-cu11[gpu,cu11]
Or install the CPU version without CUDA supported:
pip install deepmd-kit[cpu]
The LAMMPS module and the i-Pi driver are only provided on Linux and macOS. To install LAMMPS and/or i-Pi, add lmp and/or ipi to extras:
pip install deepmd-kit[gpu,cu12,lmp,ipi]
MPICH is required for parallel running. (The macOS arm64 package doesn’t support MPI yet.)
It is suggested to install the package into an isolated environment. The supported platform includes Linux x86-64 and aarch64 with GNU C Library 2.28 or above, macOS x86-64 and arm64, and Windows x86-64. A specific version of TensorFlow which is compatible with DeePMD-kit will be also installed.
Warning
If your platform is not supported, or want to build against the installed TensorFlow, or want to enable ROCM support, please build from source.
DeePMD-kit Quick Start Tutorial
©️ Copyright 2024 @ Authors
📖 Getting Started Guide
Licensing Agreement: This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This document can be executed directly on the Bohrium Notebook. To begin,you can click the Open in Bohrium button above to quickly run this document in Bohrium.
After opening Bohrium Notebook, click the button connect .We have already set up the recommended image and the recommended machine type for you.
This is a quick start guide for “Deep Potential” molecular dynamics using DeePMD-kit, through which you can quickly understand the paradigm cycle that DeePMD-kit operates in and apply it to your projects.
Deep Potential is the convergence of machine learning and physical principles, presenting a new computational paradigm as shown in the figure below.
Figure | A new computational paradigm, composed of Molecular Modeling, Machine Learning, and High-Performance Computing (HPC).
Task
Mastering the paradigm cycle of using DeePMD-kit to establish deep potential molecular dynamics models, and following a complete case to learn how to apply it to molecular dynamics tasks.
By the end of this tutorial, you will be able to:
Prepare the formataive dataset and running scripts for training with DeePMD-kit;
Train, freeze, and test DeePMD-kit models;
Use DeePMD-kit in Lammps for calculations;
Work through this tutorial. It will take you 20 minutes, max!
Background
In this tutorial, we will take the gaseous methane molecule as an example to provide a detailed introduction to the training and application of the Deep Potential (DP) model.
DeePMD-kit is a software tool that employs neural networks to fit potential energy models based on first-principles data for molecular dynamics simulations. Without manual intervention, it can end-to-end transform the data provided by users into a deep potential model in a matter of hours. This model can seamlessly integrate with common molecular dynamics simulation software (like LAMMPS, OpenMM, and GROMACS).
DeePMD-kit significantly elevates the limits of molecular dynamics through high-performance computing and machine learning, achieving system scales of up to hundreds of millions of atoms while still maintaining the high accuracy of “ab initio” calculations. The simulation time scale is improved by at least 1000 times compared to traditional methods. Its achievements earned the 2020 ACM Gordon Bell Prize, one of the highest honors in the field of high-performance computing, and it has been used by over a thousand research groups in physics, chemistry, materials science, biology, and other fields globally.
For more detailed usage, you can refer to the DeePMD-kit’s documentation as a comprehensive reference.
In this case, the Deep Potential (DP) model was generated using the DeePMD-kit package.
Practice
Data Preparation
We have prepared the initial data for \(CH_4\) required to run DeePMD-kit computations and placed it in the DeePMD-kit_Tutorial folder. You can view the corresponding files by clicking on the dataset on the left side:
import os
# Define the dataset URL and the paths
dataset_url = "https://bohrium-api.dp.tech/ds-dl/DeePMD-kit-Tutorial-a8z5-v1.zip"
zip_file_name = "DeePMD-kit-Tutorial-a8z5-v1.zip"
dataset_directory = "DeePMD-kit_Tutorial"
local_zip_path = f"/personal/{zip_file_name}"
extract_path = "/personal/"
# Check if the dataset directory exists to avoid re-downloading and re-extracting
if not os.path.isdir(f"{extract_path}{dataset_directory}"):
# Download and extract if not exists
if not os.path.isfile(local_zip_path):
print("Downloading dataset...")
!wget -q -O {local_zip_path} {dataset_url}
print("Extracting dataset...")
!unzip -q -n {local_zip_path} -d {extract_path}
else:
print("Dataset is already downloaded and extracted.")
# Change the current working directory
os.chdir(f"{extract_path}")
print(f"Current path is: {os.getcwd()}")
Dataset is already downloaded and extracted.
Current path is: /personal
Let’s take a look at the downloaded DeePMD-kit_Tutorial folder.
! tree DeePMD-kit_Tutorial -L 1
DeePMD-kit_Tutorial
├── 00.data
├── 01.train
├── 01.train.finished
├── 02.lmp
└── 02.lmp.finished
5 directories, 0 files
There are 3 subfolders under the DeePMD-kit_Tutorial folder: 00.data, 01.train, and 02.lmp.
The 00.data folder is used to store training and testing data.
The 01.train folder contains example scripts for training models using DeePMD-kit.
The 01.train.finished folder includes the complete results of the training process.
The 02.lmp folder contains example scripts for molecular dynamics simulations using LAMMPS.
Let’s first take a look at the DeePMD-kit_Tutorial/00.data folder.
! tree DeePMD-kit_Tutorial/00.data -L 1
DeePMD-kit_Tutorial/00.data
├── abacus_md
├── training_data
└── validation_data
3 directories, 0 files
DeePMD-kit’s training data originates from first-principles calculation data, including atomic types, simulation cells, atomic coordinates, atomic forces, system energies, and virials.

In the 00.data folder, there is only the abacus_md folder, which contains data obtained through ab initio Molecular Dynamics (AIMD) simulations using ABACUS. In this tutorial, we have already completed the ab initio molecular dynamics calculations for the methane molecule for you.
Detailed information about ABACUS can be found in its documentation.
DeePMD-kit uses a compressed data format. All training data should first be converted into this format before they can be used in DeePMD-kit. This data format is explained in detail in the DeePMD-kit manual, which can be found on DeePMD-kit’s Github.
We provide a convenient tool dpdata, which can convert data generated by VASP, CP2K, Gaussian, Quantum Espresso, ABACUS, and LAMMPS into DeePMD-kit’s compressed format.
A snapshot of a molecular system that contains computational data information is called a frame. A data system comprises many frames sharing the same number of atoms and atom types.
For example, a molecular dynamics trajectory can be converted into a data system, where each timestep corresponds to one frame in the system.
Next, we use the dpdata tool to randomly split the data in abacus_md into training and validation data.
import dpdata
import numpy as np
# load data of abacus/md format
data = dpdata.LabeledSystem("DeePMD-kit_Tutorial/00.data/abacus_md", fmt="abacus/md")
print("# the data contains %d frames" % len(data))
# random choose 40 index for validation_data
rng = np.random.default_rng()
index_validation = rng.choice(201, size=40, replace=False)
# other indexes are training_data
index_training = list(set(range(201)) - set(index_validation))
data_training = data.sub_system(index_training)
data_validation = data.sub_system(index_validation)
# all training data put into directory:"training_data"
data_training.to_deepmd_npy("DeePMD-kit_Tutorial/00.data/training_data")
# all validation data put into directory:"validation_data"
data_validation.to_deepmd_npy("DeePMD-kit_Tutorial/00.data/validation_data")
print("# the training data contains %d frames" % len(data_training))
print("# the validation data contains %d frames" % len(data_validation))
# the data contains 201 frames
# the training data contains 161 frames
# the validation data contains 40 frames
As you can see, 161 frames are picked as training data, and the other 40 frames are validation dat.
Let’s take another look at the 00.data folder, where new files have been generated, which are the training and validation sets required for Deep Potential training with DeePMD-kit.
! tree DeePMD-kit_Tutorial/00.data/ -L 1
DeePMD-kit_Tutorial/00.data/
├── abacus_md
├── training_data
└── validation_data
3 directories, 0 files
! tree DeePMD-kit_Tutorial/00.data/training_data -L 1
DeePMD-kit_Tutorial/00.data/training_data
├── set.000
├── type.raw
└── type_map.raw
1 directory, 2 files
The functions of these files are as follows:
set.000: It is a directory that contains compressed format data (NumPy compressed arrays).
type.raw: It is a file that contains the types of atoms (represented as integers).
type_map.raw: It is a file that contains the names of the types of atoms.
Let’s take a look at these files.
Let’s have a look at type.raw:
! cat DeePMD-kit_Tutorial/00.data/training_data/type.raw
0
0
0
0
1
This tells us there are 5 atoms in this example, 4 atoms represented by type “0”, and 1 atom represented by type “1”. Sometimes one needs to map the integer types to atom name. The mapping can be given by the file type_map.raw
! cat DeePMD-kit_Tutorial/00.data/training_data/type_map.raw
H
C
This tells us the type “0” is named by “H”, and the type “1” is named by “C”.
More detailed documentation on using dpdata for data conversion can be found here
Prepare input script
Once the data preparation is done, we can go on with training. Now go to the training directory. DeePMD-kit requires a json format file to specify parameters for training.
# Checke dargs version and Install
!pip show dargs || pip install --upgrade dargs
# Show input.json
from deepmd.utils.argcheck import gen_args
from dargs.notebook import JSON
with open("./DeePMD-kit_Tutorial/01.train/input.json") as f:
JSON(f.read(), gen_args())
{ "_comment": "that's all", "model"model: type: dict
: { "type_map"type_map: type: typing.List[str], optional
A list of strings. Give the name to each type of atoms. It is noted that the number of atom type of training system must be less than 128 in a GPU environment. If not given, type.raw in each system should use the same type indexes, and type_map.raw will take no effect.
: [
"H",
"C"
], "descriptor"descriptor: type: dict
The descriptor of atomic environment.
: { "type"type:type: str
The type of the descritpor. See explanation below.
- loc_frame: Defines a local frame at each atom, and the compute the descriptor as local coordinates under this frame.
- se_e2_a: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor.
- se_e2_r: Used by the smooth edition of Deep Potential. Only the distance between atoms is used to construct the descriptor.
- se_e3: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Three-body embedding will be used by this descriptor.
- se_a_tpe: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Type embedding will be used by this descriptor.
- se_atten: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Attention mechanism will be used by this descriptor.
- se_atten_v2: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Attention mechanism with new modifications will be used by this descriptor.
- se_a_mask: Used by the smooth edition of Deep Potential. It can accept a variable number of atoms in a frame (Non-PBC system). aparam are required as an indicator matrix for the real/virtual sign of input atoms.
- hybrid: Concatenate of a list of descriptors as a new descriptor.
: "se_e2_a", "sel"sel: type: str | typing.List[int], optional, default: auto
This parameter set the number of selected neighbors for each type of atom. It can be:
- List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
- str. Can be "auto:factor" or "auto". "factor" is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the "factor". Finally the number is wraped up to 4 divisible. The option "auto" is equivalent to "auto:1.1".
: "auto", "rcut_smth"rcut_smth: type: float, optional, default: 0.5
Where to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
: 0.5, "rcut"rcut: type: float, optional, default: 6.0
The cut-off radius.
: 6.0, "neuron"neuron: type: typing.List[int], optional, default: [10, 20, 40]
Number of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
: [
25,
50,
100
], "resnet_dt"resnet_dt: type: bool, optional, default: False
Whether to use a "Timestep" in the skip connection
: false, "axis_neuron"axis_neuron: type: int, optional, default: 4, alias: n_axis_neuron
Size of the submatrix of G (embedding matrix).
: 16, "seed"seed: type: NoneType | int, optional
Random seed for parameter initialization
: 1, "_comment": " that's all" }, "fitting_net"fitting_net: type: dict
The fitting of physical properties.
: { "neuron"neuron: type: typing.List[int], optional, default: [120, 120, 120], alias: n_neuron
The number of neurons in each hidden layers of the fitting net. When two hidden layers are of the same size, a skip connection is built.
: [
240,
240,
240
], "resnet_dt"resnet_dt: type: bool, optional, default: True
Whether to use a "Timestep" in the skip connection
: true, "seed"seed: type: NoneType | int, optional
Random seed for parameter initialization of the fitting net
: 1, "_comment": " that's all" }, "_comment": " that's all" }, "learning_rate"learning_rate: type: dict, optional
The definitio of learning rate
: { "type"type:type: str, default: exp
The type of the learning rate.
: "exp", "decay_steps"decay_steps: type: int, optional, default: 5000
The learning rate is decaying every this number of training steps.
: 50, "start_lr"start_lr: type: float, optional, default: 0.001
The learning rate at the start of the training.
: 0.001, "stop_lr"stop_lr: type: float, optional, default: 1e-08
The desired learning rate at the end of the training.
: 3.51e-08, "_comment": "that's all" }, "loss"loss: type: dict, optional
The definition of loss function. The loss type should be set to tensor, ener or left unset.
: { "type"type:type: str, default: ener
The type of the loss. When the fitting type is ener, the loss type should be set to ener or left unset. When the fitting type is dipole or polar, the loss type should be set to tensor.
: "ener", "start_pref_e"start_pref_e: type: float | int, optional, default: 0.02
The prefactor of energy loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the energy label should be provided by file energy.npy in each data system. If both start_pref_e and limit_pref_e are set to 0, then the energy will be ignored.
: 0.02, "limit_pref_e"limit_pref_e: type: float | int, optional, default: 1.0
The prefactor of energy loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
: 1, "start_pref_f"start_pref_f: type: float | int, optional, default: 1000
The prefactor of force loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the force label should be provided by file force.npy in each data system. If both start_pref_f and limit_pref_f are set to 0, then the force will be ignored.
: 1000, "limit_pref_f"limit_pref_f: type: float | int, optional, default: 1.0
The prefactor of force loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
: 1, "start_pref_v"start_pref_v: type: float | int, optional, default: 0.0
The prefactor of virial loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the virial label should be provided by file virial.npy in each data system. If both start_pref_v and limit_pref_v are set to 0, then the virial will be ignored.
: 0, "limit_pref_v"limit_pref_v: type: float | int, optional, default: 0.0
The prefactor of virial loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
: 0, "_comment": " that's all" }, "training"training: type: dict
The training options.
: { "training_data"training_data: type: dict, optional
Configurations of training data.
: { "systems"systems: type: str | typing.List[str]
The data systems for training. This key can be provided with a list that specifies the systems, or be provided with a string by which the prefix of all systems are given and the list of the systems is automatically generated.
: [
"../00.data/training_data"
], "batch_size"batch_size: type: str | typing.List[int] | int, optional, default: auto
This key can be
- list: the length of which is the same as the systems
- int: all systems
- string "auto": automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than 32.
- string "auto:N": automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than N.
- string "mixed:N": the batch data will be sampled from all systems and merged into a mixed system with the batch size N. Only support the se_atten descriptor.
If MPI is used, the value should be considered as the batch size per task.
: "auto", "_comment": "that's all" }, "validation_data"validation_data: type: NoneType | dict, optional, default: None
Configurations of validation data. Similar to that of training data, except that a numb_btch argument may be configured
: { "systems"systems: type: str | typing.List[str]
The data systems for validation. This key can be provided with a list that specifies the systems, or be provided with a string by which the prefix of all systems are given and the list of the systems is automatically generated.
: [
"../00.data/validation_data"
], "batch_size"batch_size: type: str | typing.List[int] | int, optional, default: auto
This key can be
- list: the length of which is the same as the systems
- int: all systems
- string "auto": automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than 32.
- string "auto:N": automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than N.
: "auto", "numb_btch"numb_btch: type: int, optional, default: 1, alias: numb_batch
An integer that specifies the number of batches to be sampled for each validation period.
: 1, "_comment": "that's all" }, "numb_steps"numb_steps: type: int, alias: stop_batch
Number of training batch. Each training uses one batch of data.
: 10000, "seed"seed: type: NoneType | int, optional
The random seed for getting frames from the training data set.
: 10, "disp_file"disp_file: type: str, optional, default: lcurve.out
The file for printing learning curve.
: "lcurve.out", "disp_freq"disp_freq: type: int, optional, default: 1000
The frequency of printing learning curve.
: 200, "save_freq"save_freq: type: int, optional, default: 1000
The frequency of saving check point.
: 1000, "_comment": "that's all" }}DeePMD-kit requires a json format file to specify parameters for training.
In the model section, the parameters of embedding and fitting networks are specified.
"model":{
"type_map": ["H", "C"],
"descriptor":{
"type": "se_e2_a",
"rcut": 6.00,
"rcut_smth": 0.50,
"sel": "auto",
"neuron": [25, 50, 100],
"resnet_dt": false,
"axis_neuron": 16,
"seed": 1,
"_comment": "that's all"
},
"fitting_net":{
"neuron": [240, 240, 240],
"resnet_dt": true,
"seed": 1,
"_comment": "that's all"
},
"_comment": "that's all"'
},
The explanation for some of the parameters is as follows:
Parameter | Expiation |
|---|---|
type_map | the name of each type of atom |
descriptor > type | the type of descriptor |
descriptor > rcut | cut-off radius |
descriptor > rcut_smth | where the smoothing starts |
descriptor > sel | the maximum number of type i atoms in the cut-off radius |
descriptor > neuron | size of the embedding neural network |
descriptor > axis_neuron | the size of the submatrix of G (embedding matrix) |
fitting_net > neuron | size of the fitting neural network |
The se_e2_a descriptor is used to train the DP model. The item neurons set the size of the descriptors and fitting network to [25, 50, 100] and [240, 240, 240], respectively. The components in local environment to smoothly go to zero from 0.5 to 6 Å.
The following are the parameters that specify the learning rate and loss function.
"learning_rate" :{
"type": "exp",
"decay_steps": 50,
"start_lr": 0.001,
"stop_lr": 3.51e-8,
"_comment": "that's all"
},
"loss" :{
"type": "ener",
"start_pref_e": 0.02,
"limit_pref_e": 1,
"start_pref_f": 1000,
"limit_pref_f": 1,
"start_pref_v": 0,
"limit_pref_v": 0,
"_comment": "that's all"
},
In the loss function, pref_e increases from 0.02 to 1, and pref_f decreases from 1000 to 1 progressively, which means that the force term dominates at the beginning, while energy and virial terms become important at the end. This strategy is very effective and reduces the total training time. pref_v is set to 0 , indicating that no virial data are included in the training process. The starting learning rate, stop learning rate, and decay steps are set to 0.001, 3.51e-8, and 50, respectively. The model is trained for 10000 steps.
The training parameters are given in the following
"training" : {
"training_data": {
"systems": ["../00.data/training_data"],
"batch_size": "auto",
"_comment": "that's all"
},
"validation_data":{
"systems": ["../00.data/validation_data/"],
"batch_size": "auto",
"numb_btch": 1,
"_comment": "that's all"
},
"numb_steps": 10000,
"seed": 10,
"disp_file": "lcurve.out",
"disp_freq": 200,
"save_freq": 10000,
},
More detailed docs about Data conversion can be found here
Train a model
After the training script is prepared, we can start the training with DeePMD-kit by simply running
# ########## Time Warning: 120 secs,C32_CPU ; 13 mins ,C2_CPU ##########
! cd DeePMD-kit_Tutorial/01.train/ && dp train input.json
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
DEEPMD INFO Calculate neighbor statistics... (add --skip-neighbor-stat to skip this step)
DEEPMD INFO training data with min nbor dist: 1.0460506586976848
DEEPMD INFO training data with max nbor size: [4 1]
DEEPMD INFO _____ _____ __ __ _____ _ _ _
DEEPMD INFO | __ \ | __ \ | \/ || __ \ | | (_)| |
DEEPMD INFO | | | | ___ ___ | |__) || \ / || | | | ______ | | __ _ | |_
DEEPMD INFO | | | | / _ \ / _ \| ___/ | |\/| || | | ||______|| |/ /| || __|
DEEPMD INFO | |__| || __/| __/| | | | | || |__| | | < | || |_
DEEPMD INFO |_____/ \___| \___||_| |_| |_||_____/ |_|\_\|_| \__|
DEEPMD INFO Please read and cite:
DEEPMD INFO Wang, Zhang, Han and E, Comput.Phys.Comm. 228, 178-184 (2018)
DEEPMD INFO Zeng et al, J. Chem. Phys., 159, 054801 (2023)
DEEPMD INFO See https://deepmd.rtfd.io/credits/ for details.
DEEPMD INFO installed to: /root/miniconda3/envs/deepmd
DEEPMD INFO source : v2.2.7
DEEPMD INFO source brach: HEAD
DEEPMD INFO source commit: 839f4fe7
DEEPMD INFO source commit at: 2023-10-27 21:10:24 +0800
DEEPMD INFO build float prec: double
DEEPMD INFO build variant: cpu
DEEPMD INFO build with tf inc: /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/include;/root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/../../../../include
DEEPMD INFO build with tf lib:
DEEPMD INFO ---Summary of the training---------------------------------------
DEEPMD INFO running on: bohrium-21213-1088639
DEEPMD INFO computing device: cpu:0
DEEPMD INFO Count of visible GPU: 0
DEEPMD INFO num_intra_threads: 0
DEEPMD INFO num_inter_threads: 0
DEEPMD INFO -----------------------------------------------------------------
DEEPMD INFO ---Summary of DataSystem: training -----------------------------------------------
DEEPMD INFO found 1 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../00.data/training_data 5 7 23 1.000 T
DEEPMD INFO --------------------------------------------------------------------------------------
DEEPMD INFO ---Summary of DataSystem: validation -----------------------------------------------
DEEPMD INFO found 1 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../00.data/validation_data 5 7 5 1.000 T
DEEPMD INFO --------------------------------------------------------------------------------------
DEEPMD INFO training without frame parameter
DEEPMD INFO data stating... (this step may take long time)
DEEPMD INFO built lr
DEEPMD INFO built network
DEEPMD INFO built training
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
DEEPMD INFO initialize model from scratch
DEEPMD INFO start training at lr 1.00e-03 (== 1.00e-03), decay_step 50, decay_rate 0.950006, final lr will be 3.51e-08
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/train/trainer.py:1197: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.
Instructions for updating:
tf.py_func is deprecated in TF V2. Instead, there are two
options available in V2.
- tf.py_function takes a python function which manipulates tf eager
tensors instead of numpy arrays. It's easy to convert a tf eager tensor to
an ndarray (just call tensor.numpy()) but having access to eager tensors
means `tf.py_function`s can use accelerators such as GPUs as well as
being differentiable using a gradient tape.
- tf.numpy_function maintains the semantics of the deprecated tf.py_func
(it is not differentiable, and manipulates numpy arrays). It drops the
stateful argument making all functions stateful.
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/train/trainer.py:1197: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.
Instructions for updating:
tf.py_func is deprecated in TF V2. Instead, there are two
options available in V2.
- tf.py_function takes a python function which manipulates tf eager
tensors instead of numpy arrays. It's easy to convert a tf eager tensor to
an ndarray (just call tensor.numpy()) but having access to eager tensors
means `tf.py_function`s can use accelerators such as GPUs as well as
being differentiable using a gradient tape.
- tf.numpy_function maintains the semantics of the deprecated tf.py_func
(it is not differentiable, and manipulates numpy arrays). It drops the
stateful argument making all functions stateful.
DEEPMD INFO batch 200 training time 17.53 s, testing time 0.05 s, total wall time 18.41 s
DEEPMD INFO batch 400 training time 14.96 s, testing time 0.05 s, total wall time 15.11 s
DEEPMD INFO batch 600 training time 15.47 s, testing time 0.05 s, total wall time 15.65 s
DEEPMD INFO batch 800 training time 14.25 s, testing time 0.04 s, total wall time 14.41 s
DEEPMD INFO batch 1000 training time 15.49 s, testing time 0.05 s, total wall time 15.65 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 1200 training time 16.33 s, testing time 0.08 s, total wall time 17.33 s
DEEPMD INFO batch 1400 training time 14.31 s, testing time 0.05 s, total wall time 14.47 s
DEEPMD INFO batch 1600 training time 16.54 s, testing time 0.05 s, total wall time 16.72 s
DEEPMD INFO batch 1800 training time 16.90 s, testing time 0.09 s, total wall time 17.09 s
DEEPMD INFO batch 2000 training time 17.20 s, testing time 0.06 s, total wall time 17.37 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 2200 training time 14.29 s, testing time 0.04 s, total wall time 14.83 s
DEEPMD INFO batch 2400 training time 13.11 s, testing time 0.04 s, total wall time 13.29 s
DEEPMD INFO batch 2600 training time 12.93 s, testing time 0.04 s, total wall time 13.08 s
DEEPMD INFO batch 2800 training time 14.58 s, testing time 0.04 s, total wall time 14.74 s
DEEPMD INFO batch 3000 training time 13.21 s, testing time 0.04 s, total wall time 13.35 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 3200 training time 14.40 s, testing time 0.07 s, total wall time 15.14 s
DEEPMD INFO batch 3400 training time 13.08 s, testing time 0.04 s, total wall time 13.23 s
DEEPMD INFO batch 3600 training time 12.93 s, testing time 0.06 s, total wall time 13.13 s
DEEPMD INFO batch 3800 training time 15.23 s, testing time 0.05 s, total wall time 15.43 s
DEEPMD INFO batch 4000 training time 13.20 s, testing time 0.04 s, total wall time 13.35 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 4200 training time 14.82 s, testing time 0.05 s, total wall time 16.06 s
DEEPMD INFO batch 4400 training time 14.26 s, testing time 0.05 s, total wall time 14.42 s
DEEPMD INFO batch 4600 training time 15.50 s, testing time 0.05 s, total wall time 15.66 s
DEEPMD INFO batch 4800 training time 14.12 s, testing time 0.05 s, total wall time 14.29 s
DEEPMD INFO batch 5000 training time 15.71 s, testing time 0.05 s, total wall time 15.88 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 5200 training time 14.36 s, testing time 0.07 s, total wall time 15.40 s
DEEPMD INFO batch 5400 training time 15.77 s, testing time 0.05 s, total wall time 15.93 s
DEEPMD INFO batch 5600 training time 14.12 s, testing time 0.05 s, total wall time 14.29 s
DEEPMD INFO batch 5800 training time 15.53 s, testing time 0.04 s, total wall time 15.70 s
DEEPMD INFO batch 6000 training time 15.39 s, testing time 0.09 s, total wall time 15.58 s
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/training/saver.py:1066: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to delete files with this prefix.
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/training/saver.py:1066: remove_checkpoint (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.
Instructions for updating:
Use standard file APIs to delete files with this prefix.
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 6200 training time 14.74 s, testing time 0.05 s, total wall time 15.64 s
DEEPMD INFO batch 6400 training time 15.24 s, testing time 0.09 s, total wall time 15.44 s
DEEPMD INFO batch 6600 training time 14.29 s, testing time 0.05 s, total wall time 14.48 s
DEEPMD INFO batch 6800 training time 15.46 s, testing time 0.09 s, total wall time 15.66 s
DEEPMD INFO batch 7000 training time 15.34 s, testing time 0.05 s, total wall time 15.54 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 7200 training time 15.63 s, testing time 0.05 s, total wall time 16.19 s
DEEPMD INFO batch 7400 training time 14.71 s, testing time 0.06 s, total wall time 14.90 s
DEEPMD INFO batch 7600 training time 15.96 s, testing time 0.05 s, total wall time 16.12 s
DEEPMD INFO batch 7800 training time 19.68 s, testing time 0.06 s, total wall time 19.92 s
DEEPMD INFO batch 8000 training time 15.81 s, testing time 0.07 s, total wall time 16.00 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 8200 training time 13.62 s, testing time 0.04 s, total wall time 14.54 s
DEEPMD INFO batch 8400 training time 13.23 s, testing time 0.04 s, total wall time 13.38 s
DEEPMD INFO batch 8600 training time 14.90 s, testing time 0.04 s, total wall time 15.08 s
DEEPMD INFO batch 8800 training time 13.19 s, testing time 0.04 s, total wall time 13.34 s
DEEPMD INFO batch 9000 training time 13.78 s, testing time 0.09 s, total wall time 14.00 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 9200 training time 13.76 s, testing time 0.04 s, total wall time 14.41 s
DEEPMD INFO batch 9400 training time 13.06 s, testing time 0.04 s, total wall time 13.20 s
DEEPMD INFO batch 9600 training time 14.23 s, testing time 0.04 s, total wall time 14.42 s
DEEPMD INFO batch 9800 training time 13.72 s, testing time 0.05 s, total wall time 13.88 s
DEEPMD INFO batch 10000 training time 13.92 s, testing time 0.09 s, total wall time 14.12 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO average training time: 0.0737 s/batch (exclude first 200 batches)
DEEPMD INFO finished training
DEEPMD INFO wall time: 756.650 s
On the screen, you will see the information of the data system(s)
DEEPMD INFO -----------------------------------------------------------------
DEEPMD INFO ---Summary of DataSystem: training ----------------------------------
DEEPMD INFO found 1 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../00.data/training_data 5 7 23 1.000 T
DEEPMD INFO -------------------------------------------------------------------------
DEEPMD INFO ---Summary of DataSystem: validation ----------------------------------
DEEPMD INFO found 1 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../00.data/validation_data 5 7 5 1.000 T
DEEPMD INFO -------------------------------------------------------------------------
and the starting and final learning rate of this training
DEEPMD INFO start training at lr 1.00e-03 (== 1.00e-03), decay_step 50, decay_rate 0.950006, final lr will be 3.51e-08
If everything works fine, you will see, on the screen, information printed every 1000 steps, like
DEEPMD INFO batch 200 training time 6.04 s, testing time 0.02 s
DEEPMD INFO batch 400 training time 4.80 s, testing time 0.02 s
DEEPMD INFO batch 600 training time 4.80 s, testing time 0.02 s
DEEPMD INFO batch 800 training time 4.78 s, testing time 0.02 s
DEEPMD INFO batch 1000 training time 4.77 s, testing time 0.02 s
DEEPMD INFO saved checkpoint model.ckpt
DEEPMD INFO batch 1200 training time 4.47 s, testing time 0.02 s
DEEPMD INFO batch 1400 training time 4.49 s, testing time 0.02 s
DEEPMD INFO batch 1600 training time 4.45 s, testing time 0.02 s
DEEPMD INFO batch 1800 training time 4.44 s, testing time 0.02 s
DEEPMD INFO batch 2000 training time 4.46 s, testing time 0.02 s
DEEPMD INFO saved checkpoint model.ckpt
They present the training and testing time counts. At the end of the 1000th batch, the model is saved in Tensorflow’s checkpoint file model.ckpt. At the same time, the training and testing errors are presented in file lcurve.out.
The file contains 8 columns, form left to right, are the training step, the validation loss, training loss, root mean square (RMS) validation error of energy, RMS training error of energy, RMS validation error of force, RMS training error of force and the learning rate. The RMS error (RMSE) of the energy is normalized by number of atoms in the system.
head -n 2 lcurve.out
# step rmse_val rmse_trn rmse_e_val rmse_e_trn rmse_f_val rmse_f_trn lr
0 2.02e+01 1.51e+01 1.37e-01 1.41e-01 6.40e-01 4.79e-01 1.0e-03
and
$ tail -n 2 lcurve.out
9800 2.45e-02 4.02e-02 3.20e-04 3.88e-04 2.40e-02 3.94e-02 4.3e-08
10000 4.60e-02 3.76e-02 8.65e-04 5.35e-04 4.52e-02 3.69e-02 3.5e-08
Volumes 4, 5 and 6, 7 present energy and force training and testing errors, respectively.
! cd DeePMD-kit_Tutorial/01.train.finished/ && head -n 2 lcurve.out && tail -n 2 lcurve.out
# step rmse_val rmse_trn rmse_e_val rmse_e_trn rmse_f_val rmse_f_trn lr
0 1.79e+01 2.26e+01 1.35e-01 1.33e-01 5.67e-01 7.15e-01 1.0e-03
9800 3.53e-02 2.64e-02 5.75e-04 3.01e-04 3.46e-02 2.59e-02 4.3e-08
10000 2.76e-02 2.25e-02 4.83e-04 1.62e-04 2.71e-02 2.21e-02 3.5e-08
The loss function can be visualized to monitor the training process.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
with open("./DeePMD-kit_Tutorial/01.train.finished/lcurve.out") as f:
headers = f.readline().split()[1:]
lcurve = pd.DataFrame(
np.loadtxt("./DeePMD-kit_Tutorial/01.train.finished/lcurve.out"), columns=headers
)
legends = ["rmse_e_val", "rmse_e_trn", "rmse_f_val", "rmse_f_trn"]
for legend in legends:
plt.loglog(lcurve["step"], lcurve[legend], label=legend)
plt.legend()
plt.xlabel("Training steps")
plt.ylabel("Loss")
plt.show()
Freeze a model
At the end of the training, the model parameters saved in TensorFlow’s checkpoint file should be frozen as a model file that is usually ended with extension .pb. Simply execute
## Navigate to the DeePMD-kit_Tutorial/01.train/ Directory to Freeze the Model
! cd DeePMD-kit_Tutorial/01.train.finished/ && dp freeze -o graph.pb
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
DEEPMD WARNING The following nodes are not in the graph: {'fitting_attr/aparam_nall', 'spin_attr/ntypes_spin'}. Skip freezeing these nodes. You may be freezing a checkpoint generated by an old version.
DEEPMD INFO The following nodes will be frozen: ['descrpt_attr/rcut', 'model_attr/model_version', 'o_atom_virial', 'model_attr/tmap', 'model_attr/model_type', 'o_force', 'o_energy', 'train_attr/min_nbor_dist', 'model_type', 't_mesh', 'fitting_attr/daparam', 'train_attr/training_script', 'fitting_attr/dfparam', 'o_atom_energy', 'descrpt_attr/ntypes', 'o_virial']
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/entrypoints/freeze.py:370: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.convert_variables_to_constants`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/entrypoints/freeze.py:370: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.convert_variables_to_constants`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py:925: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.extract_sub_graph`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py:925: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.extract_sub_graph`
DEEPMD INFO 1222 ops in the final graph.
and it will output a model file named graph.pb in the current directory.
Compress a model
To enhance computational efficiency with DP models, compression significantly accelerates DP-based calculations and reduces memory usage. We can compress the model by running:
## Navigate to the DeePMD-kit_Tutorial/01.train/ Directory to Compress the Model
! cd DeePMD-kit_Tutorial/01.train.finished/ && dp compress -i graph.pb -o compress.pb
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
DEEPMD INFO
DEEPMD INFO stage 1: compress the model
DEEPMD INFO _____ _____ __ __ _____ _ _ _
DEEPMD INFO | __ \ | __ \ | \/ || __ \ | | (_)| |
DEEPMD INFO | | | | ___ ___ | |__) || \ / || | | | ______ | | __ _ | |_
DEEPMD INFO | | | | / _ \ / _ \| ___/ | |\/| || | | ||______|| |/ /| || __|
DEEPMD INFO | |__| || __/| __/| | | | | || |__| | | < | || |_
DEEPMD INFO |_____/ \___| \___||_| |_| |_||_____/ |_|\_\|_| \__|
DEEPMD INFO Please read and cite:
DEEPMD INFO Wang, Zhang, Han and E, Comput.Phys.Comm. 228, 178-184 (2018)
DEEPMD INFO Zeng et al, J. Chem. Phys., 159, 054801 (2023)
DEEPMD INFO See https://deepmd.rtfd.io/credits/ for details.
DEEPMD INFO installed to: /root/miniconda3/envs/deepmd
DEEPMD INFO source : v2.2.7
DEEPMD INFO source brach: HEAD
DEEPMD INFO source commit: 839f4fe7
DEEPMD INFO source commit at: 2023-10-27 21:10:24 +0800
DEEPMD INFO build float prec: double
DEEPMD INFO build variant: cpu
DEEPMD INFO build with tf inc: /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/include;/root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/../../../../include
DEEPMD INFO build with tf lib:
DEEPMD INFO ---Summary of the training---------------------------------------
DEEPMD INFO running on: bohrium-21213-1088639
DEEPMD INFO computing device: cpu:0
DEEPMD INFO Count of visible GPU: 0
DEEPMD INFO num_intra_threads: 0
DEEPMD INFO num_inter_threads: 0
DEEPMD INFO -----------------------------------------------------------------
DEEPMD INFO training without frame parameter
DEEPMD INFO training data with lower boundary: [-0.92929175 -0.99957951]
DEEPMD INFO training data with upper boundary: [1.97058099 1.10195361]
DEEPMD INFO built lr
DEEPMD INFO built network
DEEPMD INFO built training
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
DEEPMD INFO initialize model from scratch
DEEPMD INFO finished compressing
DEEPMD INFO
DEEPMD INFO stage 2: freeze the model
DEEPMD WARNING The following nodes are not in the graph: {'spin_attr/ntypes_spin', 'fitting_attr/aparam_nall'}. Skip freezeing these nodes. You may be freezing a checkpoint generated by an old version.
DEEPMD INFO The following nodes will be frozen: ['train_attr/min_nbor_dist', 'o_energy', 'descrpt_attr/rcut', 'o_force', 'model_type', 'fitting_attr/daparam', 'model_attr/tmap', 'o_atom_energy', 'descrpt_attr/ntypes', 'o_virial', 't_mesh', 'model_attr/model_type', 'fitting_attr/dfparam', 'o_atom_virial', 'train_attr/training_script', 'model_attr/model_version']
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/entrypoints/freeze.py:370: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.convert_variables_to_constants`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/entrypoints/freeze.py:370: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.convert_variables_to_constants`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py:925: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.extract_sub_graph`
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/framework/convert_to_constants.py:925: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.compat.v1.graph_util.extract_sub_graph`
DEEPMD INFO 858 ops in the final graph.
Test a model
We can check the quality of the trained model by running
! cd DeePMD-kit_Tutorial/01.train.finished/ && dp test -m graph.pb -s ../00.data/validation_data
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/utils/batch_size.py:62: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/utils/batch_size.py:62: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
DEEPMD WARNING You can use the environment variable DP_INFER_BATCH_SIZE tocontrol the inference batch size (nframes * natoms). The default value is 1024.
DEEPMD INFO # ---------------output of dp test---------------
DEEPMD INFO # testing system : ../00.data/validation_data
DEEPMD INFO # number of test data : 40
DEEPMD INFO Energy MAE : 1.473845e-03 eV
DEEPMD INFO Energy RMSE : 2.007936e-03 eV
DEEPMD INFO Energy MAE/Natoms : 2.947689e-04 eV
DEEPMD INFO Energy RMSE/Natoms : 4.015871e-04 eV
DEEPMD INFO Force MAE : 2.146239e-02 eV/A
DEEPMD INFO Force RMSE : 2.748797e-02 eV/A
DEEPMD INFO Virial MAE : 2.879183e-02 eV
DEEPMD INFO Virial RMSE : 3.817983e-02 eV
DEEPMD INFO Virial MAE/Natoms : 5.758366e-03 eV
DEEPMD INFO Virial RMSE/Natoms : 7.635965e-03 eV
DEEPMD INFO # -----------------------------------------------
The correlation between predicted data and original data can also be calculated.
import dpdata
training_systems = dpdata.LabeledSystem(
"./DeePMD-kit_Tutorial/00.data/training_data", fmt="deepmd/npy"
)
predict = training_systems.predict("./DeePMD-kit_Tutorial/01.train.finished/graph.pb")
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/tensorflow/python/compat/v2_compat.py:107: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
WARNING:root:To get the best performance, it is recommended to adjust the number of threads by setting the environment variables OMP_NUM_THREADS, TF_INTRA_OP_PARALLELISM_THREADS, and TF_INTER_OP_PARALLELISM_THREADS. See https://deepmd.rtfd.io/parallelism/ for more information.
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/utils/batch_size.py:62: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
2024-03-24 23:05:17.177887: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE4.1 SSE4.2 AVX AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2024-03-24 23:05:17.179243: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
2024-03-24 23:05:17.197330: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:354] MLIR V1 optimization pass is not enabled
WARNING:tensorflow:From /root/miniconda3/envs/deepmd/lib/python3.10/site-packages/deepmd/utils/batch_size.py:62: is_gpu_available (from tensorflow.python.framework.test_util) is deprecated and will be removed in a future version.
Instructions for updating:
Use `tf.config.list_physical_devices('GPU')` instead.
WARNING:deepmd.utils.batch_size:You can use the environment variable DP_INFER_BATCH_SIZE tocontrol the inference batch size (nframes * natoms). The default value is 1024.
import matplotlib.pyplot as plt
import numpy as np
plt.scatter(training_systems["energies"], predict["energies"])
x_range = np.linspace(plt.xlim()[0], plt.xlim()[1])
plt.plot(x_range, x_range, "r--", linewidth=0.25)
plt.xlabel("Energy of DFT")
plt.ylabel("Energy predicted by deep potential")
plt.plot()
[]
Run MD with LAMMPS
The model can drive molecular dynamics in LAMMPS.
! ls
! cd ./DeePMD-kit_Tutorial/02.lmp && cp ../01.train.finished/graph.pb ./ && tree -L 1
DeePMD-kit_Tutorial
.
├── ch4.dump
├── conf.lmp
├── graph.pb
├── in.lammps
└── log.lammps
0 directories, 5 files
Here conf.lmp gives the initial configuration of a gas phase methane MD simulation, and the file in.lammps is the LAMMPS input script. One may check in.lammps and finds that it is a rather standard LAMMPS input file for a MD simulation, with only two exception lines:
pair_style deepmd graph.pb
pair_coeff * *
where the pair style deepmd is invoked and the model file graph.pb is provided, which means the atomic interaction will be computed by the DP model that is stored in the file graph.pb.
In an environment with a compatibable version of LAMMPS, the deep potential molecular dynamics can be performed via
lmp -i input.lammps
! cd ./DeePMD-kit_Tutorial/02.lmp && lmp -i in.lammps
LAMMPS (2 Aug 2023 - Update 1)
OMP_NUM_THREADS environment is not set. Defaulting to 1 thread. (src/comm.cpp:98)
using 1 OpenMP thread(s) per MPI task
Loaded 1 plugins from /root/miniconda3/envs/deepmd/lib/deepmd_lmp
Reading data file ...
triclinic box = (0 0 0) to (10.114259 10.263124 10.216793) with tilt (0.036749877 0.13833062 -0.056322169)
1 by 1 by 1 MPI processor grid
reading atoms ...
5 atoms
read_data CPU = 0.002 seconds
DeePMD-kit WARNING: Environmental variable OMP_NUM_THREADS is not set. Tune OMP_NUM_THREADS for the best performance. See https://deepmd.rtfd.io/parallelism/ for more information.
Summary of lammps deepmd module ...
>>> Info of deepmd-kit:
installed to: /root/miniconda3/envs/deepmd
source: v2.2.7
source branch: HEAD
source commit: 839f4fe7
source commit at: 2023-10-27 21:10:24 +0800
surpport model ver.:1.1
build variant: cpu
build with tf inc: /root/miniconda3/envs/deepmd/include;/root/miniconda3/envs/deepmd/include
build with tf lib: /root/miniconda3/envs/deepmd/lib/libtensorflow_cc.so
set tf intra_op_parallelism_threads: 0
set tf inter_op_parallelism_threads: 0
>>> Info of lammps module:
use deepmd-kit at: /root/miniconda3/envs/deepmdDeePMD-kit WARNING: Environmental variable OMP_NUM_THREADS is not set. Tune OMP_NUM_THREADS for the best performance. See https://deepmd.rtfd.io/parallelism/ for more information.
2024-03-24 23:05:49.768736: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: SSE4.1 SSE4.2 AVX AVX2 AVX512F FMA
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2024-03-24 23:05:49.770401: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.
2024-03-24 23:05:49.817983: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:354] MLIR V1 optimization pass is not enabled
INVALID_ARGUMENT: Tensor spin_attr/ntypes_spin:0, specified in either feed_devices or fetch_devices was not found in the Graph
>>> Info of model(s):
using 1 model(s): graph.pb
rcut in model: 6
ntypes in model: 2
CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE
Your simulation uses code contributions which should be cited:
- USER-DEEPMD package:
The log file lists these citations in BibTeX format.
CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE-CITE
Generated 0 of 1 mixed pair_coeff terms from geometric mixing rule
Neighbor list info ...
update: every = 10 steps, delay = 0 steps, check = no
max neighbors/atom: 2000, page size: 100000
master list distance cutoff = 7
ghost atom cutoff = 7
binsize = 3.5, bins = 3 3 3
1 neighbor lists, perpetual/occasional/extra = 1 0 0
(1) pair deepmd, perpetual
attributes: full, newton on
pair build: full/bin/atomonly
stencil: full/bin/3d
bin: standard
Setting up Verlet run ...
Unit style : metal
Current step : 0
Time step : 0.001
Per MPI rank memory allocation (min/avg/max) = 2.559 | 2.559 | 2.559 Mbytes
Step PotEng KinEng TotEng Temp Press Volume
0 -219.77409 0.025852029 -219.74824 50 -799.80566 1060.5429
100 -219.77101 0.02250472 -219.7485 43.526023 -563.15562 1060.5429
200 -219.77525 0.025722761 -219.74953 49.749984 -55.768826 1060.5429
300 -219.78111 0.030123111 -219.75098 58.260632 415.50143 1060.5429
400 -219.78545 0.03264184 -219.7528 63.132067 724.77655 1060.5429
500 -219.7897 0.034591934 -219.75511 66.903712 664.01323 1060.5429
600 -219.78944 0.031599794 -219.75784 61.116661 307.82983 1060.5429
700 -219.78389 0.023121639 -219.76076 44.719197 -166.66606 1060.5429
800 -219.77712 0.013122374 -219.764 25.379775 -493.10259 1060.5429
900 -219.7791 0.011293959 -219.76781 21.843468 -609.86395 1060.5429
1000 -219.78712 0.01531002 -219.77181 29.610866 -422.5828 1060.5429
1100 -219.7939 0.018709632 -219.77519 36.186003 -61.443156 1060.5429
1200 -219.79395 0.016606919 -219.77734 32.11918 331.62678 1060.5429
1300 -219.79132 0.012642575 -219.77868 24.451803 505.6361 1060.5429
1400 -219.79314 0.013255468 -219.77989 25.637191 381.73541 1060.5429
1500 -219.79509 0.014397006 -219.78069 27.845022 48.696022 1060.5429
1600 -219.79313 0.012485864 -219.78064 24.148711 -302.67659 1060.5429
1700 -219.78841 0.0085717658 -219.77983 16.578516 -476.08062 1060.5429
1800 -219.78663 0.0081557171 -219.77847 15.773843 -407.83792 1060.5429
1900 -219.78715 0.010996426 -219.77615 21.268013 -98.699573 1060.5429
2000 -219.78836 0.016278673 -219.77209 31.484324 293.02315 1060.5429
2100 -219.78819 0.022161035 -219.76603 42.861306 587.40225 1060.5429
2200 -219.79165 0.031838471 -219.75981 61.578284 543.58893 1060.5429
2300 -219.79343 0.038239208 -219.75519 73.957846 104.54643 1060.5429
2400 -219.78301 0.031060153 -219.75195 60.072951 -293.72903 1060.5429
2500 -219.77209 0.022352657 -219.74974 43.231919 -606.61353 1060.5429
2600 -219.76604 0.017305685 -219.74873 33.47065 -623.66583 1060.5429
2700 -219.77552 0.026563069 -219.74895 51.375211 -332.34033 1060.5429
2800 -219.78594 0.0362724 -219.74967 70.153875 120.73427 1060.5429
2900 -219.78868 0.038558744 -219.75012 74.575856 542.93567 1060.5429
3000 -219.78351 0.03281317 -219.75069 63.463433 746.24646 1060.5429
3100 -219.78106 0.028937414 -219.75212 55.967395 583.87016 1060.5429
3200 -219.77929 0.025275432 -219.75402 48.884814 128.24387 1060.5429
3300 -219.77781 0.022017978 -219.75579 42.584622 -395.55332 1060.5429
3400 -219.77696 0.019305132 -219.75765 37.33775 -679.74745 1060.5429
3500 -219.78369 0.023714356 -219.75997 45.86556 -656.9891 1060.5429
3600 -219.79244 0.030071312 -219.76237 58.160448 -354.34542 1060.5429
3700 -219.79168 0.027557568 -219.76412 53.298657 199.00964 1060.5429
3800 -219.78639 0.021137515 -219.76525 40.881734 596.54224 1060.5429
3900 -219.77923 0.012972221 -219.76626 25.089367 713.41996 1060.5429
4000 -219.78185 0.014202505 -219.76765 27.46884 430.83529 1060.5429
4100 -219.78477 0.016041208 -219.76872 31.025047 -28.605377 1060.5429
4200 -219.78545 0.016332231 -219.76912 31.587909 -457.5328 1060.5429
4300 -219.78602 0.016882726 -219.76914 32.652612 -608.55966 1060.5429
4400 -219.78949 0.020680419 -219.76881 39.99767 -456.72943 1060.5429
4500 -219.79121 0.023411938 -219.7678 45.280658 -79.406734 1060.5429
4600 -219.7882 0.022574198 -219.76562 43.660398 414.11955 1060.5429
4700 -219.78521 0.022736692 -219.76248 43.974676 663.73939 1060.5429
4800 -219.7834 0.025050214 -219.75835 48.449222 598.39611 1060.5429
4900 -219.78291 0.030199797 -219.75271 58.408949 203.75805 1060.5429
5000 -219.77611 0.030245158 -219.74586 58.496682 -300.80549 1060.5429
Loop time of 38.8363 on 1 procs for 5000 steps with 5 atoms
Performance: 11.124 ns/day, 2.158 hours/ns, 128.746 timesteps/s, 643.728 atom-step/s
104.3% CPU use with 1 MPI tasks x 1 OpenMP threads
MPI task timing breakdown:
Section | min time | avg time | max time |%varavg| %total
---------------------------------------------------------------
Pair | 38.703 | 38.703 | 38.703 | 0.0 | 99.66
Neigh | 0.0079815 | 0.0079815 | 0.0079815 | 0.0 | 0.02
Comm | 0.0334 | 0.0334 | 0.0334 | 0.0 | 0.09
Output | 0.0065195 | 0.0065195 | 0.0065195 | 0.0 | 0.02
Modify | 0.070599 | 0.070599 | 0.070599 | 0.0 | 0.18
Other | | 0.01491 | | | 0.04
Nlocal: 5 ave 5 max 5 min
Histogram: 1 0 0 0 0 0 0 0 0 0
Nghost: 130 ave 130 max 130 min
Histogram: 1 0 0 0 0 0 0 0 0 0
Neighs: 0 ave 0 max 0 min
Histogram: 1 0 0 0 0 0 0 0 0 0
FullNghs: 20 ave 20 max 20 min
Histogram: 1 0 0 0 0 0 0 0 0 0
Total # of neighbors = 20
Ave neighs/atom = 4
Neighbor list builds = 500
Dangerous builds not checked
Total wall time: 0:00:39
Installation
Easy install
There are various easy methods to install DeePMD-kit. Choose one that you prefer. If you want to build by yourself, jump to the next two sections.
After your easy installation, DeePMD-kit (dp) and LAMMPS (lmp) will be available to execute. You can try dp -h and lmp -h to see the help. mpirun is also available considering you may want to train models or run LAMMPS in parallel.
Note
Note: The off-line packages and conda packages require the GNU C Library 2.17 or above. The GPU version requires compatible NVIDIA driver to be installed in advance. It is possible to force conda to override detection when installation, but these requirements are still necessary during runtime. You can refer to DeepModeling conda FAQ for more information.
Install off-line packages
Both CPU and GPU version offline packages are available in the Releases page.
Some packages are splited into two files due to size limit of GitHub. One may merge them into one after downloading:
cat deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh.0 deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh.1 > deepmd-kit-2.2.9-cuda118-Linux-x86_64.sh
One may enable the environment using
conda activate /path/to/deepmd-kit
Install with conda
DeePMD-kit is available with conda. Install Anaconda, Miniconda, or miniforge first. You can refer to DeepModeling conda FAQ for how to setup a conda environment.
conda-forge channel
DeePMD-kit is available on the conda-forge channel:
conda create -n deepmd deepmd-kit lammps horovod -c conda-forge
The supported platforms include Linux x86-64, macOS x86-64, and macOS arm64. Read conda-forge FAQ to learn how to install CUDA-enabled packages.
Official channel
Danger
Deprecated since version 3.0.0: The official channel will be deprecated since 3.0.0. Old packages will still be available at https://conda.deepmodeling.com. Maintainers will build packages in the conda-forge organization together with other conda-forge members.
One may create an environment that contains the CPU version of DeePMD-kit and LAMMPS:
conda create -n deepmd deepmd-kit=*=*cpu libdeepmd=*=*cpu lammps -c https://conda.deepmodeling.com -c defaults
Or one may want to create a GPU environment containing CUDA Toolkit:
conda create -n deepmd deepmd-kit=*=*gpu libdeepmd=*=*gpu lammps cudatoolkit=11.6 horovod -c https://conda.deepmodeling.com -c defaults
One could change the CUDA Toolkit version from 10.2 or 11.6.
One may specify the DeePMD-kit version such as 2.2.9 using
conda create -n deepmd deepmd-kit=2.2.9=*cpu libdeepmd=2.2.9=*cpu lammps horovod -c https://conda.deepmodeling.com -c defaults
One may enable the environment using
conda activate deepmd
Install with docker
A docker for installing the DeePMD-kit is available here.
To pull the CPU version:
docker pull ghcr.io/deepmodeling/deepmd-kit:2.1.1_cpu
To pull the GPU version:
docker pull ghcr.io/deepmodeling/deepmd-kit:2.1.1_cuda11.6_gpu
To pull the ROCm version:
docker pull deepmodeling/dpmdkit-rocm:dp2.0.3-rocm4.5.2-tf2.6-lmp29Sep2021
Install Python interface with pip
If you have no existing TensorFlow installed, you can use pip to install the pre-built package of the Python interface with CUDA 12 supported:
pip install deepmd-kit[gpu,cu12]
cu12 is required only when CUDA Toolkit and cuDNN were not installed.
To install the package built against CUDA 11.8, use
pip install deepmd-kit-cu11[gpu,cu11]
Or install the CPU version without CUDA supported:
pip install deepmd-kit[cpu]
The LAMMPS module and the i-Pi driver are only provided on Linux and macOS. To install LAMMPS and/or i-Pi, add lmp and/or ipi to extras:
pip install deepmd-kit[gpu,cu12,lmp,ipi]
MPICH is required for parallel running. (The macOS arm64 package doesn’t support MPI yet.)
It is suggested to install the package into an isolated environment. The supported platform includes Linux x86-64 and aarch64 with GNU C Library 2.28 or above, macOS x86-64 and arm64, and Windows x86-64. A specific version of TensorFlow which is compatible with DeePMD-kit will be also installed.
Warning
If your platform is not supported, or want to build against the installed TensorFlow, or want to enable ROCM support, please build from source.
Install from source code
Please follow our GitHub webpage to download the latest released version and development version.
Or get the DeePMD-kit source code by git clone
cd /some/workspace
git clone https://github.com/deepmodeling/deepmd-kit.git deepmd-kit
For convenience, you may want to record the location of the source to a variable, saying deepmd_source_dir by
cd deepmd-kit
deepmd_source_dir=`pwd`
Install the python interface
Install Tensorflow’s python interface
First, check the python version on your machine
python --version
We follow the virtual environment approach to install TensorFlow’s Python interface. The full instruction can be found on the official TensorFlow website. TensorFlow 1.8 or later is supported. Now we assume that the Python interface will be installed to the virtual environment directory $tensorflow_venv
virtualenv -p python3 $tensorflow_venv
source $tensorflow_venv/bin/activate
pip install --upgrade pip
pip install --upgrade tensorflow
It is important that every time a new shell is started and one wants to use DeePMD-kit, the virtual environment should be activated by
source $tensorflow_venv/bin/activate
if one wants to skip out of the virtual environment, he/she can do
deactivate
If one has multiple python interpreters named something like python3.x, it can be specified by, for example
virtualenv -p python3.8 $tensorflow_venv
If one does not need the GPU support of DeePMD-kit and is concerned about package size, the CPU-only version of TensorFlow should be installed by
pip install --upgrade tensorflow-cpu
To verify the installation, run
python -c "import tensorflow as tf;print(tf.reduce_sum(tf.random.normal([1000, 1000])))"
One should remember to activate the virtual environment every time he/she uses DeePMD-kit.
One can also build the TensorFlow Python interface from source for custom hardware optimization, such as CUDA, ROCM, or OneDNN support.
Install the DeePMD-kit’s python interface
Check the compiler version on your machine
gcc --version
The compiler GCC 4.8 or later is supported in the DeePMD-kit. Note that TensorFlow may have specific requirements for the compiler version to support the C++ standard version and _GLIBCXX_USE_CXX11_ABI used by TensorFlow. It is recommended to use the same compiler version as TensorFlow, which can be printed by python -c "import tensorflow;print(tensorflow.version.COMPILER_VERSION)".
Execute
cd $deepmd_source_dir
pip install .
One may set the following environment variables before executing pip:
Environment variables | Allowed value | Default value | Usage |
|---|---|---|---|
DP_VARIANT |
|
| Build CPU variant or GPU variant with CUDA or ROCM support. |
CUDAToolkit_ROOT | Path | Detected automatically | The path to the CUDA toolkit directory. CUDA 9.0 or later is supported. NVCC is required. |
ROCM_ROOT | Path | Detected automatically | The path to the ROCM toolkit directory. |
TENSORFLOW_ROOT | Path | Detected automatically | The path to TensorFlow Python library. By default the installer only finds TensorFlow under user site-package directory ( |
DP_ENABLE_NATIVE_OPTIMIZATION | 0, 1 | 0 | Enable compilation optimization for the native machine’s CPU type. Do not enable it if generated code will run on different CPUs. |
CMAKE_ARGS | str | - | Additional CMake arguments |
<LANG>FLAGS ( | str | - | Default compilation flags to be used when compiling |
To test the installation, one should first jump out of the source directory
cd /some/other/workspace
then execute
dp -h
It will print the help information like
usage: dp [-h] {train,freeze,test} ...
DeePMD-kit: A deep learning package for many-body potential energy
representation and molecular dynamics
optional arguments:
-h, --help show this help message and exit
Valid subcommands:
{train,freeze,test}
train train a model
freeze freeze the model
test test the model
Install horovod and mpi4py
Horovod and mpi4py are used for parallel training. For better performance on GPU, please follow the tuning steps in Horovod on GPU.
# With GPU, prefer NCCL as a communicator.
HOROVOD_WITHOUT_GLOO=1 HOROVOD_WITH_TENSORFLOW=1 HOROVOD_GPU_OPERATIONS=NCCL HOROVOD_NCCL_HOME=/path/to/nccl pip install horovod mpi4py
If your work in a CPU environment, please prepare runtime as below:
# By default, MPI is used as communicator.
HOROVOD_WITHOUT_GLOO=1 HOROVOD_WITH_TENSORFLOW=1 pip install horovod mpi4py
To ensure Horovod has been built with proper framework support enabled, one can invoke the horovodrun --check-build command, e.g.,
$ horovodrun --check-build
Horovod v0.22.1:
Available Frameworks:
[X] TensorFlow
[X] PyTorch
[ ] MXNet
Available Controllers:
[X] MPI
[X] Gloo
Available Tensor Operations:
[X] NCCL
[ ] DDL
[ ] CCL
[X] MPI
[X] Gloo
Since version 2.0.1, Horovod and mpi4py with MPICH support are shipped with the installer.
If you don’t install Horovod, DeePMD-kit will fall back to serial mode.
Install the C++ interface
If one does not need to use DeePMD-kit with Lammps or I-Pi, then the python interface installed in the previous section does everything and he/she can safely skip this section.
Install Tensorflow’s C++ interface (optional)
Since TensorFlow 2.12, TensorFlow C++ library (libtensorflow_cc) is packaged inside the Python library. Thus, you can skip building TensorFlow C++ library manually. If that does not work for you, you can still build it manually.
The C++ interface of DeePMD-kit was tested with compiler GCC >= 4.8. It is noticed that the I-Pi support is only compiled with GCC >= 4.8. Note that TensorFlow may have specific requirements for the compiler version.
First, the C++ interface of Tensorflow should be installed. It is noted that the version of Tensorflow should be consistent with the python interface. You may follow the instruction or run the script $deepmd_source_dir/source/install/build_tf.py to install the corresponding C++ interface.
Install DeePMD-kit’s C++ interface
Now go to the source code directory of DeePMD-kit and make a building place.
cd $deepmd_source_dir/source
mkdir build
cd build
The installation requires CMake 3.16 or later for the CPU version, CMake 3.23 or later for the CUDA support, and CMake 3.21 or later for the ROCM support. One can install CMake via pip if it is not installed or the installed version does not satisfy the requirement:
pip install -U cmake
I assume you have activated the TensorFlow Python environment and want to install DeePMD-kit into path $deepmd_root, then execute CMake
cmake -DUSE_TF_PYTHON_LIBS=TRUE -DCMAKE_INSTALL_PREFIX=$deepmd_root ..
If you specify -DUSE_TF_PYTHON_LIBS=FALSE, you need to give the location where TensorFlow’s C++ interface is installed to -DTENSORFLOW_ROOT=${tensorflow_root}.
One may add the following arguments to cmake:
CMake Aurgements | Allowed value | Default value | Usage |
|---|---|---|---|
-DTENSORFLOW_ROOT=<value> | Path | - | The Path to TensorFlow’s C++ interface. |
-DCMAKE_INSTALL_PREFIX=<value> | Path | - | The Path where DeePMD-kit will be installed. |
-DUSE_CUDA_TOOLKIT=<value> |
|
| If |
-DCUDAToolkit_ROOT=<value> | Path | Detected automatically | The path to the CUDA toolkit directory. CUDA 9.0 or later is supported. NVCC is required. |
-DUSE_ROCM_TOOLKIT=<value> |
|
| If |
-DCMAKE_HIP_COMPILER_ROCM_ROOT=<value> | Path | Detected automatically | The path to the ROCM toolkit directory. |
-DLAMMPS_SOURCE_ROOT=<value> | Path | - | Only neccessary for LAMMPS plugin mode. The path to the LAMMPS source code. LAMMPS 8Apr2021 or later is supported. If not assigned, the plugin mode will not be enabled. |
-DUSE_TF_PYTHON_LIBS=<value> |
|
| If |
-DENABLE_NATIVE_OPTIMIZATION=<value> |
|
| Enable compilation optimization for the native machine’s CPU type. Do not enable it if generated code will run on different CPUs. |
-DCMAKE_<LANG>_FLAGS=<value> ( | str | - | Default compilation flags to be used when compiling |
If the CMake has been executed successfully, then run the following make commands to build the package:
make -j4
make install
Option -j4 means using 4 processes in parallel. You may want to use a different number according to your hardware.
If everything works fine, you will have the executable and libraries installed in $deepmd_root/bin and $deepmd_root/lib
$ ls $deepmd_root/bin
$ ls $deepmd_root/lib
Install from pre-compiled C library
DeePMD-kit provides pre-compiled C library package (libdeepmd_c.tar.gz) in each release. It can be used to build the LAMMPS plugin and GROMACS patch, as well as many third-party software packages, without building TensorFlow and DeePMD-kit on one’s own. It can be downloaded via the shell command:
wget https://github.com/deepmodeling/deepmd-kit/releases/latest/download/libdeepmd_c.tar.gz
tar xzf libdeepmd_c.tar.gz
The library is built in Linux (GLIBC 2.17) with CUDA 12.2 (libdeepmd_c.tar.gz) or 11.8 (libdeepmd_c_cu11.tar.gz). It’s noted that this package does not contain CUDA Toolkit and cuDNN, so one needs to download them from the NVIDIA website.
Use Pre-compiled C Library to build the LAMMPS plugin and GROMACS patch
When one installs DeePMD-kit’s C++ interface, one can use the CMake argument DEEPMD_C_ROOT to the path libdeepmd_c.
cd $deepmd_source_dir/source
mkdir build
cd build
cmake -DDEEPMD_C_ROOT=/path/to/libdeepmd_c -DCMAKE_INSTALL_PREFIX=$deepmd_root ..
make -j8
make install
Then one can follow the manual Install LAMMPS and/or Install GROMACS.
Install LAMMPS
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.
Install LAMMPS’s DeePMD-kit module (built-in mode)
Before following this section, DeePMD-kit C++ interface should have be installed.
DeePMD-kit provides a module for running MD simulations with LAMMPS. Now make the DeePMD-kit module for LAMMPS.
cd $deepmd_source_dir/source/build
make lammps
DeePMD-kit will generate a module called USER-DEEPMD in the build directory, which supports either double or single float precision interface. Now download the LAMMPS code, and uncompress it.
cd /some/workspace
wget https://github.com/lammps/lammps/archive/stable_2Aug2023_update3.tar.gz
tar xf stable_2Aug2023_update3.tar.gz
The source code of LAMMPS is stored in the directory lammps-stable_2Aug2023_update3.
Then, you can build LAMMPS with either make or CMake.
With make
Now go into the LAMMPS code and copy the DeePMD-kit module like this
cd lammps-stable_2Aug2023_update3/src/
cp -r $deepmd_source_dir/source/build/USER-DEEPMD .
make yes-kspace
make yes-extra-fix
make yes-user-deepmd
You can enable any other package you want. Now build LAMMPS
make mpi -j4
If everything works fine, you will end up with an executable lmp_mpi.
./lmp_mpi -h
The DeePMD-kit module can be removed from the LAMMPS source code by
make no-user-deepmd
With CMake
Now go into the LAMMPS directory and create a directory called build:
mkdir -p lammps-stable_2Aug2023_update3/build/
cd lammps-stable_2Aug2023_update3/build/
Patch the LAMMPS CMakeLists.txt file:
echo "include(${deepmd_source_dir}/source/lmp/builtin.cmake)" >> ../cmake/CMakeLists.txt
It’s expected to see one extra line in the end of CMakeLists.txt.
Now build LAMMPS. You can install any other package you want.
cmake -D LAMMPS_INSTALL_RPATH=ON -D BUILD_SHARED_LIBS=yes -D CMAKE_INSTALL_PREFIX=${deepmd_root} -DCMAKE_PREFIX_PATH=${deepmd_root} ../cmake
make -j4
make install
If everything works fine, you will end up with an executable ${deepmd_root}/bin/lmp.
${deepmd_root}/bin/lmp -h
Install LAMMPS (plugin mode)
Starting from 8Apr2021, LAMMPS also provides a plugin mode, allowing one to build LAMMPS and a plugin separately.
Now download the LAMMPS code (8Apr2021 or later), and uncompress it:
cd /some/workspace
wget https://github.com/lammps/lammps/archive/stable_2Aug2023_update3.tar.gz
tar xf stable_2Aug2023_update3.tar.gz
The source code of LAMMPS is stored in the directory lammps-stable_2Aug2023_update3. The directory of the source code should be specified as the CMAKE argument LAMMPS_SOURCE_ROOT during installation of the DeePMD-kit C++ interface. Now go into the LAMMPS directory and create a directory called build
mkdir -p lammps-stable_2Aug2023_update3/build/
cd lammps-stable_2Aug2023_update3/build/
Now build LAMMPS. Note that PLUGIN must be enabled, and BUILD_SHARED_LIBS must be set to yes. You can install any other package you want.
cmake -D PKG_PLUGIN=ON -D LAMMPS_INSTALL_RPATH=ON -D BUILD_SHARED_LIBS=yes -D CMAKE_INSTALL_PREFIX=${deepmd_root} -D CMAKE_INSTALL_LIBDIR=lib -D CMAKE_INSTALL_FULL_LIBDIR=${deepmd_root}/lib ../cmake
make -j4
make install
If everything works fine, you will end up with an executable ${deepmd_root}/bin/lmp.
${deepmd_root}/bin/lmp -h
Note
If ${tensorflow_root}, ${deepmd_root}, or the path to TensorFlow Python package if applicable is different from the prefix of LAMMPS, you need to append the library path to RUNPATH of liblammps.so. For example, use patchelf >= 0.13
patchelf --add-rpath "${tensorflow_root}/lib" liblammps.so
Install i-PI
The i-PI works in a client-server model. The i-PI provides the server for integrating the replica positions of atoms, while the DeePMD-kit provides a client named dp_ipi that computes the interactions (including energy, forces and virials). The server and client communicate via the Unix domain socket or the Internet socket. Full documentation for i-PI can be found here. The source code and a complete installation guide for i-PI can be found here. To use i-PI with already existing drivers, install and update using Pip:
pip install -U i-PI
Test with Pytest:
pip install pytest
pytest --pyargs ipi.tests
Install GROMACS with DeepMD
Before following this section, DeePMD-kit C++ interface should have be installed.
Patch source code of GROMACS
Download the source code of a supported GROMACS version (2020.2) from https://manual.gromacs.org/2020.2/download.html. Run the following command:
export PATH=$PATH:$deepmd_kit_root/bin
dp_gmx_patch -d $gromacs_root -v $version -p
where deepmd_kit_root is the directory where the latest version of DeePMD-kit is installed, and gromacs_root refers to the source code directory of GROMACS. And version represents the version of GROMACS, where only 2020.2 is supported now. If attempting to patch another version of GROMACS you will still need to set version to 2020.2 as this is the only supported version, we cannot guarantee that patching other versions of GROMACS will work.
Compile GROMACS with deepmd-kit
The C++ interface of Deepmd-kit 2.x and TensorFlow 2.x are required. And be aware that only DeePMD-kit with high precision is supported now since we cannot ensure single precision is enough for a GROMACS simulation. Here is a sample compile script:
#!/bin/bash
export CC=/usr/bin/gcc
export CXX=/usr/bin/g++
export CMAKE_PREFIX_PATH="/path/to/fftw-3.3.9" # fftw libraries
mkdir build
cd build
cmake3 .. -DCMAKE_CXX_STANDARD=14 \ # not required, but c++14 seems to be more compatible with higher version of tensorflow
-DGMX_MPI=ON \
-DGMX_GPU=CUDA \ # Gromacs on ROCm has not been fully developed yet
-DCUDAToolkit_ROOT=/path/to/cuda \
-DCMAKE_INSTALL_PREFIX=/path/to/gromacs-2020.2-deepmd
make -j
make install
Building conda packages
Danger
Deprecated since version 3.0.0: The official channel will be deprecated since 3.0.0. Refer to conda-forge documentation for how to contribute and build packages locally.
One may want to keep both convenience and personalization of the DeePMD-kit. To achieve this goal, one can consider building conda packages. We provide building scripts in deepmd-kit-recipes organization. These building tools are driven by conda-build and conda-smithy.
For example, if one wants to turn on MPIIO package in LAMMPS, go to lammps-feedstock repository and modify recipe/build.sh. -D PKG_MPIIO=OFF should be changed to -D PKG_MPIIO=ON. Then go to the main directory and execute
./build-locally.py
This requires that Docker has been installed. After the building, the packages will be generated in build_artifacts/linux-64 and build_artifacts/noarch, and then one can install then executing
conda create -n deepmd lammps -c file:///path/to/build_artifacts -c https://conda.deepmodeling.com -c nvidia
One may also upload packages to one’s Anaconda channel, so they can be installed on other machines:
anaconda upload /path/to/build_artifacts/linux-64/*.tar.bz2 /path/to/build_artifacts/noarch/*.tar.bz2
Install Node.js interface
DeePMD-kit has an inference interface for Node.js, the most common programming language in the world, via a wrapper of the header-only C++ interface created by SWIG.
Install from npm
npm i deepmd-kit
# Or if you want to install globally
npm i -g deepmd-kit
Build from source
Before building DeePMD-kit, install Node.js, SWIG (v4.1.0 for Node.js v12-v18 support), and node-gyp globally.
When using CMake to build DeePMD-kit from source, set argument BUILD_NODEJS_IF=ON and NODEJS_INCLUDE_DIRS=/path/to/nodejs/include (the path to the include directory of Node.js):
cmake -D BUILD_NODEJS_IF=ON \
-D NODEJS_INCLUDE_DIRS=/path/to/nodejs/include \
.. # and other arguments
make
make install
After installing DeePMD-kit, two files, bind.gyp and deepmdJAVASCRIPT_wrap.cxx will be generated in $deepmd_source_dir/source/nodejs.
Go to this directory, and install the Node.js package globally:
cd $deepmd_source_dir/source/nodejs
npm i
npm link
The deepmd-kit package should be globally available in Node.js environments:
const deepmd = require("deepmd-kit");
Easy install the latest development version
DeePMD-kit is actively developed in the devel branch. The documentation of the latest version matches the devel branch.
The following is the way to install the pre-compiled packages without building from source. All of them are built with GitHub Actions.
Install with docker
The devel tag is used to mark the latest development version with CUDA 12.2 support:
docker pull ghcr.io/deepmodeling/deepmd-kit:devel
For CUDA 11.8 support, use the devel_cu11 tag.
Install with pip
Below is an one-line shell command to download the artifact containing wheels and install it with pip:
pip install -U --pre deepmd-kit[gpu,cu12,lmp] --extra-index-url https://deepmodeling.github.io/deepmd-kit/simple
cu12 and lmp are optional, which is the same as the stable version.
Download pre-compiled C Library
The pre-comiled C library can be downloaded from here, or via a shell command:
wget https://nightly.link/deepmodeling/deepmd-kit/workflows/package_c/devel/libdeepmd_c-0-libdeepmd_c.tar.gz.zip && unzip libdeepmd_c-0-libdeepmd_c.tar.gz.zip
Pre-release conda-forge packages
Pre-release conda-forge packages are in conda-forge/label/deepmd-kit_dev or conda-forge/label/deepmd-kit_rc channels, other than the conda-forge channel. See conda-forge documentation for more information.
Data
In this section, we will introduce how to convert the DFT-labeled data into the data format used by DeePMD-kit.
The DeePMD-kit organizes data in systems. Each system is composed of a number of frames. One may roughly view a frame as a snapshot of an MD trajectory, but it does not necessarily come from an MD simulation. A frame records the coordinates and types of atoms, cell vectors if the periodic boundary condition is assumed, energy, atomic forces and virials. It is noted that the frames in one system share the same number of atoms with the same type.
System
DeePMD-kit takes a system as the data structure. A snapshot of a system is called a frame. A system may contain multiple frames with the same atom types and numbers, i.e. the same formula (like H2O). To contains data with different formulas, one usually needs to divide data into multiple systems, which may sometimes result in sparse-frame systems. See a new system format to further combine different systems with the same atom numbers, when training with descriptor se_atten.
A system should contain system properties, input frame properties, and labeled frame properties. The system property contains the following property:
ID | Property | Raw file | Required/Optional | Shape | Description |
|---|---|---|---|---|---|
type | Atom type indexes | type.raw | Required | Natoms | Integers that start with 0. If both the training parameter type_map is set and |
type_map | Atom type names | type_map.raw | Optional | Ntypes | Atom names that map to atom type, which is unnecessary to be contained in the periodic table. Only works when the training parameter type_map is set |
nopbc | Non-periodic system | nopbc | Optional | 1 | If True, this system is non-periodic; otherwise it’s periodic |
The input frame properties contain the following property, the first axis of which is the number of frames:
ID | Property | Raw file | Unit | Required/Optional | Shape | Description |
|---|---|---|---|---|---|---|
coord | Atomic coordinates | coord.raw | Å | Required | Nframes * Natoms * 3 | |
box | Boxes | box.raw | Å | Required if periodic | Nframes * 3 * 3 | in the order |
fparam | Extra frame parameters | fparam.raw | Any | Optional | Nframes * Any | |
aparam | Extra atomic parameters | aparam.raw | Any | Optional | Nframes * aparam * Any | |
numb_copy | Each frame is copied by the | prob.raw | 1 | Optional | Nframes | Integer; Default is 1 for all frames |
The labeled frame properties are listed as follows, all of which will be used for training if and only if the loss function contains such property:
ID | Property | Raw file | Unit | Shape | Description |
|---|---|---|---|---|---|
energy | Frame energies | energy.raw | eV | Nframes | |
force | Atomic forces | force.raw | eV/Å | Nframes * Natoms * 3 | |
virial | Frame virial | virial.raw | eV | Nframes * 9 | in the order |
atom_ener | Atomic energies | atom_ener.raw | eV | Nframes * Natoms | |
atom_pref | Weights of atomic forces | atom_pref.raw | 1 | Nframes * Natoms | |
dipole | Frame dipole | dipole.raw | Any | Nframes * 3 | |
atomic_dipole | Atomic dipole | atomic_dipole.raw | Any | Nframes * Natoms * 3 | |
polarizability | Frame polarizability | polarizability.raw | Any | Nframes * 9 | in the order |
atomic_polarizability | Atomic polarizability | atomic_polarizability.raw | Any | Nframes * Natoms * 9 | in the order |
drdq | Partial derivative of atomic coordinates with respect to generalized coordinates | drdq.raw | 1 | Nframes * Natoms * 3 * Ngen_coords |
In general, we always use the following convention of units:
Property | Unit |
|---|---|
Time | ps |
Length | Å |
Energy | eV |
Force | eV/Å |
Virial | eV |
Pressure | Bar |
Formats of a system
Two binary formats, NumPy and HDF5, are supported for training. The raw format is not directly supported, but a tool is provided to convert data from the raw format to the NumPy format.
NumPy format
In a system with the Numpy format, the system properties are stored as text files ending with .raw, such as type.raw and type_map.raw, under the system directory. If one needs to train a non-periodic system, an empty nopbc file should be put under the system directory. Both input and labeled frame properties are saved as the NumPy binary data (NPY) files ending with .npy in each of the set.* directories. Take an example, a system may contain the following files:
type.raw
type_map.raw
nopbc
set.000/coord.npy
set.000/energy.npy
set.000/force.npy
set.001/coord.npy
set.001/energy.npy
set.001/force.npy
We assume that the atom types do not change in all frames. It is provided by type.raw, which has one line with the types of atoms written one by one. The atom types should be integers. For example the type.raw of a system that has 2 atoms with 0 and 1:
$ cat type.raw
0 1
Sometimes one needs to map the integer types to atom names. The mapping can be given by the file type_map.raw. For example
$ cat type_map.raw
O H
The type 0 is named by "O" and the type 1 is named by "H".
For training models with descriptor se_atten, a new system format is supported to put together the frame-sparse systems with the same atom number.
HDF5 format
A system with the HDF5 format has the same structure as the Numpy format, but in an HDF5 file, a system is organized as an HDF5 group. The file name of a Numpy file is the key in an HDF5 file, and the data is the value of the key. One needs to use # in a DP path to divide the path to the HDF5 file and the HDF5 path:
/path/to/data.hdf5#/H2O
Here, /path/to/data.hdf5 is the file path and /H2O is the HDF5 path. All HDF5 paths should start with /. There should be some data in the H2O group, such as /H2O/type.raw and /H2O/set.000/force.npy.
An HDF5 file with a large number of systems has better performance than multiple NumPy files in a large cluster.
Raw format and data conversion
A raw file is a plain text file with each information item written in one file and one frame written on one line. It’s not directly supported, but we provide a tool to convert them.
In the raw format, the property of one frame is provided per line, ending with .raw. Take an example, the default files that provide box, coordinate, force, energy and virial are box.raw, coord.raw, force.raw, energy.raw and virial.raw, respectively. Here is an example of force.raw:
$ cat force.raw
-0.724 2.039 -0.951 0.841 -0.464 0.363
6.737 1.554 -5.587 -2.803 0.062 2.222
-1.968 -0.163 1.020 -0.225 -0.789 0.343
This force.raw contains 3 frames with each frame having the forces of 2 atoms, thus it has 3 lines and 6 columns. Each line provides all the 3 force components of 2 atoms in 1 frame. The first three numbers are the 3 force components of the first atom, while the second three numbers are the 3 force components of the second atom. Other files are organized similarly. The number of lines of all raw files should be identical.
One can use the script $deepmd_source_dir/data/raw/raw_to_set.sh to convert the prepared raw files to the NumPy format. For example, if we have a raw file that contains 6000 frames,
$ ls
box.raw coord.raw energy.raw force.raw type.raw virial.raw
$ $deepmd_source_dir/data/raw/raw_to_set.sh 2000
nframe is 6000
nline per set is 2000
will make 3 sets
making set 0 ...
making set 1 ...
making set 2 ...
$ ls
box.raw coord.raw energy.raw force.raw set.000 set.001 set.002 type.raw virial.raw
It generates three sets set.000, set.001 and set.002, with each set containing 2000 frames in the Numpy format.
Prepare data with dpdata
One can use a convenient tool dpdata to convert data directly from the output of first principle packages to the DeePMD-kit format.
To install one can execute
pip install dpdata
An example of converting data VASP data in OUTCAR format to DeePMD-kit data can be found at
$deepmd_source_dir/examples/data_conv
Switch to that directory, then one can convert data by using the following python script
import dpdata
dsys = dpdata.LabeledSystem("OUTCAR")
dsys.to("deepmd/npy", "deepmd_data", set_size=dsys.get_nframes())
get_nframes() method gets the number of frames in the OUTCAR, and the argument set_size enforces that the set size is equal to the number of frames in the system, viz. only one set is created in the system.
The data in DeePMD-kit format is stored in the folder deepmd_data.
A list of all supported data format and more nice features of dpdata can be found on the official website.
Model
Overall
Theory
A Deep Potential (DP) model, denoted by \(\mathcal{M}\), can be generally represented as
where \(\boldsymbol{y}_i\) is the fitting properties, \(\mathcal{F}\) is the fitting network, \(\mathcal{D}\) is the descriptor. \(\boldsymbol{x} = (\boldsymbol r_i, \alpha_i)\), with \(\boldsymbol r_i\) being the Cartesian coordinates and \(\alpha_i\) being the chemical species, denotes the degrees of freedom of the atom \(i\).
The indices of the neighboring atoms (i.e. atoms within a certain cutoff radius) of atom \(i\) are given by the notation \(n(i)\). Note that the Cartesian coordinates can be either under the periodic boundary condition (PBC) or in vacuum (under the open boundary condition). The network parameters are denoted by \(\boldsymbol \theta = \{\boldsymbol \theta_d, \boldsymbol \theta_f\}\), where \(\boldsymbol \theta_d\) and \(\boldsymbol\theta_f\) yield the network parameters of the descriptor (if any) and those of the fitting network, respectively. From the above equation, one may compute the global property of the system by
where \(N\) is the number of atoms in a frame. For example, if \(y_i\) represents the potential energy contribution of atom \(i\), then \(y\) gives the total potential energy of the frame.1
Instructions
A model has two parts, a descriptor that maps atomic configuration to a set of symmetry invariant features, and a fitting net that takes descriptor as input and predicts the atomic contribution to the target physical property. It’s defined in the model section of the input.json, for example,
"model": {
"type_map": ["O", "H"],
"descriptor" :{
"...": "..."
},
"fitting_net" : {
"...": "..."
}
}
The two subsections, descriptor and fitting_net, define the descriptor and the fitting net, respectively.
The type_map is optional, which provides the element names (but not necessarily same as the actual name of the element) of the corresponding atom types. A water model, as in this example, has two kinds of atoms. The atom types are internally recorded as integers, e.g., 0 for oxygen and 1 for hydrogen here. A mapping from the atom type to their names is provided by type_map.
DeePMD-kit implements the following descriptors:
se_e2_a: DeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.se_e2_r: DeepPot-SE constructed from radial information of atomic configurations. The embedding takes the distance between atoms as input.se_e3: DeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes angles between two neighboring atoms as input.se_a_mask: DeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The input frames in one system can have a varied number of atoms. Input particles are padded with virtual particles of the same length.loc_frame: Defines a local frame at each atom and compute the descriptor as local coordinates under this frame.hybrid: Concate a list of descriptors to form a new descriptor.
The fitting of the following physical properties is supported
ener: Fit the energy of the system. The force (derivative with atom positions) and the virial (derivative with the box tensor) can also be trained.dipole: The dipole moment.polar: The polarizability.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "se_e2_a"
The notation of se_e2_a is short for the Deep Potential Smooth Edition (DeepPot-SE) constructed from all information (both angular and radial) of atomic configurations. The e2 stands for the embedding with two-atoms information. This descriptor was described in detail in the DeepPot-SE paper.
Note that it is sometimes called a “two-atom embedding descriptor” which means the input of the embedding net is atomic distances. The descriptor does encode multi-body information (both angular and radial information of neighboring atoms).
Theory
The two-body embedding smooth edition of the DP descriptor \(\mathcal{D}^i \in \mathbb{R}^{M \times M_{<}}\), is usually named DeepPot-SE descriptor. It is noted that the descriptor is a multi-body representation of the local environment of the atom \(i\). We call it two-body embedding because the embedding network takes only the distance between atoms \(i\) and \(j\) (see below), but it is not implied that the descriptor takes only the pairwise information between \(i\) and its neighbors. The descriptor, using full information, is given by
where \(N_c\) is the expected maximum number of neighboring atoms, which is the same constant for all atoms over all frames. A matrix with a dimension of \(N_c\) will be padded if the number of neighboring atoms is less than \(N_c\). \(\mathcal{R}^i \in \mathbb{R}^{N_c \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as
where \(\boldsymbol{r}_{ij}=\boldsymbol{r}_j-\boldsymbol{r}_i = (x_{ij}, y_{ij}, z_{ij})\) is the relative coordinate and \(r_{ij}=\lVert \boldsymbol{r}_{ij} \lVert\) is its norm. The switching function \(s(r)\) is defined as
where \(x=\frac{r - r_s}{ r_c - r_s}\) switches from 1 at \(r_s\) to 0 at the cutoff radius \(r_c\). The switching function \(s(r)\) is smooth in the sense that the second-order derivative is continuous.
Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N_c \times M}\) consists of \(M\) nodes from the output layer of an NN function \(\mathcal{N}_ {g}\) of \(s(r_{ij})\):
where the subscript \(e,2\) is used to distinguish the NN from other NNs used in the DP model. In the above equation, the network parameters are not explicitly written. \(\mathcal{G}^i_< \in \mathbb{R}^{N_c \times M_<}\) only takes first \(M_<\) columns of \(\mathcal{G}^i\) to reduce the size of \(\mathcal D^i\). \(r_s\), \(r_c\), \(M\) and \(M_<\) are hyperparameters provided by the user. The DeepPot-SE is continuous up to the second-order derivative in its domain.1
Instructions
In this example, we will train a DeepPot-SE model for a water system. A complete training input script of this example can be found in the directory.
$deepmd_source_dir/examples/water/se_e2_a/input.json
With the training input script, data are also provided in the example directory. One may train the model with the DeePMD-kit from the directory.
The construction of the descriptor is given by section descriptor. An example of the descriptor is provided as follows
"descriptor" :{
"type": "se_e2_a",
"rcut_smth": 0.50,
"rcut": 6.00,
"sel": [46, 92],
"neuron": [25, 50, 100],
"type_one_side": true,
"axis_neuron": 16,
"resnet_dt": false,
"seed": 1
}
The type of the descriptor is set to
"se_e2_a".rcut is the cut-off radius for neighbor searching, and the rcut_smth gives where the smoothing starts.
sel gives the maximum possible number of neighbors in the cut-off radius. It is a list, the length of which is the same as the number of atom types in the system, and
sel[i]denotes the maximum possible number of neighbors with typei.The neuron specifies the size of the embedding net. From left to right the members denote the sizes of each hidden layer from the input end to the output end, respectively. If the outer layer is twice the size of the inner layer, then the inner layer is copied and concatenated, then a ResNet architecture is built between them.
If the option type_one_side is set to
true, the embedding network parameters vary by types of neighbor atoms only, so there will be \(N_\text{types}\) sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be \(N_\text{types}^2\) sets of embedding network parameters.The axis_neuron specifies the size of the submatrix of the embedding matrix, the axis matrix as explained in the DeepPot-SE paper
If the option resnet_dt is set to
true, then a timestep is used in the ResNet.seed gives the random seed that is used to generate random numbers when initializing the model parameters.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "se_e2_r"
The notation of se_e2_r is short for the Deep Potential Smooth Edition (DeepPot-SE) constructed from the radial information of atomic configurations. The e2 stands for the embedding with two-atom information.
Theory
The descriptor, using either radial-only information, is given by
where \(N_c\) is the expected maximum number of neighboring atoms, which is the same constant for all atoms over all frames. A matrix with a dimension of \(N_c\) will be padded if the number of neighboring atoms is less than \(N_c\).
Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N_c \times M}\) consists of \(M\) nodes from the output layer of an NN function \(\mathcal{N}_ {g}\) of \(s(r_{ij})\):
where \(\boldsymbol{r}_ {ij}=\boldsymbol{r}_ j-\boldsymbol{r}_ i = (x_{ij}, y_{ij}, z_{ij})\) is the relative coordinate and \(r_{ij}=\lVert \boldsymbol{r}_{ij} \lVert\) is its norm. The switching function \(s(r)\) is defined as
where \(x=\frac{r - r_s}{ r_c - r_s}\) switches from 1 at \(r_s\) to 0 at the cutoff radius \(r_c\). The switching function \(s(r)\) is smooth in the sense that the second-order derivative is continuous.
In the above equations, the network parameters are not explicitly written. \(r_s\), \(r_c\) and \(M\) are hyperparameters provided by the user. The DeepPot-SE is continuous up to the second-order derivative in its domain.1
Instructions
A complete training input script of this example can be found in the directory
$deepmd_source_dir/examples/water/se_e2_r/input.json
The training input script is very similar to that of se_e2_a. The only difference lies in the descriptor section
"descriptor": {
"type": "se_e2_r",
"sel": [46, 92],
"rcut_smth": 0.50,
"rcut": 6.00,
"neuron": [5, 10, 20],
"type_one_side": true,
"resnet_dt": false,
"seed": 1,
"_comment": " that's all"
},
The type of the descriptor is set by the key type.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "se_e3"
The notation of se_e3 is short for the Deep Potential Smooth Edition (DeepPot-SE) constructed from all information (both angular and radial) of atomic configurations. The embedding takes bond angles between a central atom and its two neighboring atoms as input (denoted by e3).
Theory
The three-body embedding DeepPot-SE descriptor incorporates bond-angle information, making the model more accurate. The descriptor \(\mathcal{D}^i\) can be represented as
where \(N_c\) is the expected maximum number of neighboring atoms, which is the same constant for all atoms over all frames. \(\mathcal{R}^i\) is constructed as
Currently, only the full information case of \(\mathcal{R}^i\) is supported by the three-body embedding. Each element of \(\mathcal{G}^i \in \mathbb{R}^{N_c \times N_c \times M}\) comes from \(M\) nodes from the output layer of an NN \(\mathcal{N}_{e,3}\) function:
where \((\theta_i)_ {jk} = (\mathcal{R}^i)_ {j,\\{2,3,4\\}}\cdot (\mathcal{R}^i)_ {k,\\{2,3,4\\}}\) considers the angle form of two neighbours (\(j\) and \(k\)). The notation \(:\) in the equation indicates the contraction between matrix \(\mathcal{R}^i(\mathcal{R}^i)^T\) and the first two dimensions of tensor \(\mathcal{G}^i\).1
Instructions
A complete training input script of this example can be found in the directory
$deepmd_source_dir/examples/water/se_e3/input.json
The training input script is very similar to that of se_e2_a. The only difference lies in the descriptor <model/descriptor> section
"descriptor": {
"type": "se_e3",
"sel": [40, 80],
"rcut_smth": 0.50,
"rcut": 6.00,
"neuron": [2, 4, 8],
"resnet_dt": false,
"seed": 1,
"_comment": " that's all"
},
The type of the descriptor is set by the key type.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "se_atten"
DPA-1: Pretraining of Attention-based Deep Potential Model for Molecular Simulation

Here we propose DPA-1, a Deep Potential model with a novel attention mechanism, which is highly effective for representing the conformation and chemical spaces of atomic systems and learning the PES.
See this paper for more information. DPA-1 is implemented as a new descriptor "se_atten" for model training, which can be used after simply editing the input.json.
Theory
Attention-based descriptor \(\mathcal{D}^i \in \mathbb{R}^{M \times M_{<}}\), which is proposed in pretrainable DPA-1 model, is given by
where \(\hat{\mathcal{G}}^i\) represents the embedding matrix \(\mathcal{G}^i\) after additional self-attention mechanism and \(\mathcal{R}^i\) is defined by the full case in the se_e2_a. Note that we obtain \(\mathcal{G}^i\) using the type embedding method by default in this descriptor.
To perform the self-attention mechanism, the queries \(\mathcal{Q}^{i,l} \in \mathbb{R}^{N_c\times d_k}\), keys \(\mathcal{K}^{i,l} \in \mathbb{R}^{N_c\times d_k}\), and values \(\mathcal{V}^{i,l} \in \mathbb{R}^{N_c\times d_v}\) are first obtained:
where \(Q_{l}\), \(K_{l}\), \(V_{l}\) represent three trainable linear transformations that output the queries and keys of dimension \(d_k\) and values of dimension \(d_v\), and \(l\) is the index of the attention layer. The input embedding matrix to the attention layers, denoted by \(\mathcal{G}^{i,0}\), is chosen as the two-body embedding matrix.
Then the scaled dot-product attention method is adopted:
where \(\varphi\left(\mathcal{Q}^{i,l}, \mathcal{K}^{i,l},\mathcal{R}^{i,l}\right) \in \mathbb{R}^{N_c\times N_c}\) is attention weights. In the original attention method, one typically has \(\varphi\left(\mathcal{Q}^{i,l}, \mathcal{K}^{i,l}\right)=\mathrm{softmax}\left(\frac{\mathcal{Q}^{i,l} (\mathcal{K}^{i,l})^{T}}{\sqrt{d_{k}}}\right)\), with \(\sqrt{d_{k}}\) being the normalization temperature. This is slightly modified to incorporate the angular information:
where \(\hat{\mathcal{R}}^{i} \in \mathbb{R}^{N_c\times 3}\) denotes normalized relative coordinates , \(\hat{\mathcal{R}}^{i}_{j} = \frac{\boldsymbol{r}_{ij}}{\lVert \boldsymbol{r}_{ij} \lVert}\) and \(\odot\) means element-wise multiplication.
Then layer normalization is added in a residual way to finally obtain the self-attention local embedding matrix \(\hat{\mathcal{G}}^{i} = \mathcal{G}^{i,L_a}\) after \(L_a\) attention layers:1
Introduction to new features of DPA-1
Next, we will list the detailed settings in input.json and the data format, especially for large systems with dozens of elements. An example of DPA-1 input can be found here.
Descriptor "se_atten"
The notation of se_atten is short for the smooth edition of Deep Potential with an attention mechanism. This descriptor was described in detail in the DPA-1 paper and the images above.
In this example, we will train a DPA-1 model for a water system. A complete training input script of this example can be found in the directory:
$deepmd_source_dir/examples/water/se_atten/input.json
With the training input script, data are also provided in the example directory. One may train the model with the DeePMD-kit from the directory.
An example of the DPA-1 descriptor is provided as follows
"descriptor" :{
"type": "se_atten",
"rcut_smth": 0.50,
"rcut": 6.00,
"sel": 120,
"neuron": [25, 50, 100],
"axis_neuron": 16,
"resnet_dt": false,
"attn": 128,
"attn_layer": 2,
"attn_mask": false,
"attn_dotr": true,
"seed": 1
}
The type of the descriptor is set to
"se_atten", which will use DPA-1 structures.rcut is the cut-off radius for neighbor searching, and the rcut_smth gives where the smoothing starts.
sel gives the maximum possible number of neighbors in the cut-off radius. It is an int. Note that this number highly affects the efficiency of training, which we usually use less than 200. (We use 120 for training 56 elements in OC2M dataset)
The neuron specifies the size of the embedding net. From left to right the members denote the sizes of each hidden layer from the input end to the output end, respectively. If the outer layer is twice the size of the inner layer, then the inner layer is copied and concatenated, then a ResNet architecture is built between them.
The axis_neuron specifies the size of the submatrix of the embedding matrix, the axis matrix as explained in the DeepPot-SE paper
If the option resnet_dt is set to
true, then a timestep is used in the ResNet.seed gives the random seed that is used to generate random numbers when initializing the model parameters.
attn sets the length of a hidden vector during scale-dot attention computation.
attn_layer sets the number of layers in attention mechanism.
attn_mask determines whether to mask the diagonal in the attention weights and False is recommended.
attn_dotr determines whether to dot the relative coordinates on the attention weights as a gated scheme, True is recommended.
Descriptor "se_atten_v2"
We highly recommend using the version 2.0 of the attention-based descriptor "se_atten_v2", which is inherited from "se_atten" but with the following parameter modifications:
"stripped_type_embedding": true,
"smooth_type_embdding": true,
"set_davg_zero": false
Practical evidence demonstrates that "se_atten_v2" offers better and more stable performance compared to "se_atten".
Fitting "ener"
DPA-1 only supports "ener" fitting type, and you can refer here for detailed information.
Type embedding
DPA-1 only supports models with type embeddings. And the default setting is as follows:
"type_embedding":{
"neuron": [8],
"resnet_dt": false,
"seed": 1
}
You can add these settings in input.json if you want to change the default ones, see here for detailed information.
Type map
For training large systems, especially those with dozens of elements, the type determines the element index of training data:
"type_map": [
"Mg",
"Al",
"Cu"
]
which should include all the elements in the dataset you want to train on.
Data format
DPA-1 supports the standard data format, which is detailed in data-conv.md and system.md. Note that in this format, only those frames with the same fingerprint (i.e. the number of atoms of different elements) can be put together as a unified system. This may lead to sparse frame numbers in those rare systems.
An ideal way is to put systems with the same total number of atoms together, which is the way we trained DPA-1 on OC2M. This system format, which is called mixed_type, is proper to put frame-sparse systems together and is slightly different from the standard one. Take an example, a mixed_type may contain the following files:
type.raw
type_map.raw
set.*/box.npy
set.*/coord.npy
set.*/energy.npy
set.*/force.npy
set.*/real_atom_types.npy
This system contains Nframes frames with the same atom number Natoms, the total number of element types contained in all frames is Ntypes. Most files are the same as those in standard formats, here we only list the distinct ones:
ID | Property | File | Required/Optional | Shape | Description |
|---|---|---|---|---|---|
/ | Atom type indexes (place holder) | type.raw | Required | Natoms | All zeros to fake the type input |
type_map | Atom type names | type_map.raw | Required | Ntypes | Atom names that map to atom type contained in all the frames, which is unnecessart to be contained in the periodic table |
type | Atom type indexes of each frame | real_atom_types.npy | Required | Nframes * Natoms | Integers that describe atom types in each frame, corresponding to indexes in type_map. |
With these edited files, one can put together frames with the same Natoms, instead of the same formula (like H2O). Note that this mixed_type format only supports se_atten descriptor.
To put frames with different Natoms into the same system, one can pad systems by adding virtual atoms whose type is -1. Virtual atoms do not contribute to any fitting property, so the atomic property of virtual atoms (e.g. forces) should be given zero.
The API to generate or transfer to mixed_type format is available on dpdata for a more convenient experience.
Training example
Here we upload the AlMgCu example shown in the paper, you can download it here: Baidu disk; Google disk.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "hybrid"
This descriptor hybridizes multiple descriptors to form a new descriptor. For example, we have a list of descriptors denoted by \(\mathcal D_1\), \(\mathcal D_2\), …, \(\mathcal D_N\), the hybrid descriptor this the concatenation of the list, i.e. \(\mathcal D = (\mathcal D_1, \mathcal D_2, \cdots, \mathcal D_N)\).
Theory
A hybrid descriptor \(\mathcal{D}^i_\text{hyb}\) concatenates multiple kinds of descriptors into one descriptor:
The list of descriptors can be different types or the same descriptors with different parameters. This way, one can set the different cutoff radii for different descriptors.1
Instructions
To use the descriptor in DeePMD-kit, one firstly set the type to hybrid, then provide the definitions of the descriptors by the items in the list,
"descriptor" :{
"type": "hybrid",
"list" : [
{
"type" : "se_e2_a",
...
},
{
"type" : "se_e2_r",
...
}
]
},
A complete training input script of this example can be found in the directory
$deepmd_source_dir/examples/water/hybrid/input.json
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Determine sel
All descriptors require to set sel, which means the expected maximum number of type-i neighbors of an atom. DeePMD-kit will allocate memory according to sel.
sel should not be too large or too small. If sel is too large, the computing will become much slower and cost more memory. If sel is not enough, the energy will be not conserved, making the accuracy of the model worse.
To determine a proper sel, one can calculate the neighbor stat of the training data before training:
dp neighbor-stat -s data -r 6.0 -t O H
where data is the directory of data, 6.0 is the cutoff radius, and O and H is the type map. The program will give the max_nbor_size. For example, max_nbor_size of the water example is [38, 72], meaning an atom may have 38 O neighbors and 72 H neighbors in the training data.
The sel should be set to a higher value than that of the training data, considering there may be some extreme geometries during MD simulations. As a result, we set sel to [46, 92] in the water example.
Fit energy
In this section, we will take $deepmd_source_dir/examples/water/se_e2_a/input.json as an example of the input file.
Theory
In the DP model, we let the fitting network \(\mathcal{F}_ 0\) maps the descriptor \(\mathcal{D}^i\) to a scalar, where the subscript \(0\) means that the output is a zero-order tensor (i.e. scalar). The model can then be used to predict the total potential energy of the system by
where the output of the fitting network is treated as the atomic potential energy contribution, i.e. \(E_i\). The output scalar can also be treated as other scalar properties defined on an atom, for example, the partial charge of atom \(i\).
In some cases, atomic-specific or frame-specific parameters, such as electron temperature, may be treated as extra input to the fitting network. We denote the atomic and frame-specific parameters by \(\boldsymbol{P}^i\in \mathbb{R}^{N_p}\) (with \(N_p\) being the dimension) and \(\boldsymbol{Q}\in \mathbb{R}^{N_q}\) (with \(N_q\) being the dimension), respectively.
The atomic force \(\boldsymbol{F}_ {i}\) and the virial tensor \(\boldsymbol{\Xi} = (\Xi_{\alpha\beta})\) (if PBC is applied) can be derived from the potential energy \(E\):
where \(r_{i,\alpha}\) and \(F_{i,\alpha}\) denotes the \(\alpha\)-th component of the coordinate and force of atom \(i\). \(h_{\alpha\beta}\) is the \(\beta\)-th component of the \(\alpha\)-th basis vector of the simulation region.
The properties \(\eta\) of the energy loss function could be energy \(E\), force \(\boldsymbol{F}\), virial \(\boldsymbol{\Xi}\), relative energy \(\Delta E\), or any combination among them, and the loss functions of them are
where \(F_{k,\alpha}\) is the \(\alpha\)-th component of the force on atom \(k\), and the superscript \(\ast\) indicates the label of the property that should be provided in advance. Using \(N\) ensures that each loss of fitting property is averaged over atomic contributions before they contribute to the total loss by weight.
If part of atoms is more important than others, for example, certain atoms play an essential role when calculating free energy profiles or kinetic isotope effects, the MSE of atomic forces with prefactors \(q_{k}\) can also be used as the loss function:
The atomic forces with larger prefactors will be fitted more accurately than those in other atoms.
If some forces are quite large, for example, forces can be greater than 60 eV/Å in high-temperature reactive simulations, one may also prefer the force loss is relative to the magnitude:
where \(\nu\) is a small constant used to protect an atom where the magnitude of \(\boldsymbol{F}^\ast_k\) is small from having a large \(L^r_F\). Benefiting from the relative force loss, small forces can be fitted more accurately.1
The fitting network
The construction of the fitting net is given by section fitting_net
"fitting_net" : {
"neuron": [240, 240, 240],
"resnet_dt": true,
"seed": 1
},
neuron specifies the size of the fitting net. If two neighboring layers are of the same size, then a ResNet architecture is built between them.
If the option resnet_dt is set to
true, then a timestep is used in the ResNet.seed gives the random seed that is used to generate random numbers when initializing the model parameters.
Loss
The loss function \(L\) for training energy is given by
where \(L_e\), \(L_f\), and \(L_v\) denote the loss in energy, forces and virials, respectively. \(p_e\), \(p_f\), and \(p_v\) give the prefactors of the energy, force and virial losses. The prefectors may not be a constant, rather it changes linearly with the learning rate. Taking the force prefactor for example, at training step \(t\), it is given by
where \(\alpha(t)\) denotes the learning rate at step \(t\). \(p_f^0\) and \(p_f^\infty\) specifies the \(p_f\) at the start of the training and the limit of \(t \to \infty\) (set by start_pref_f and limit_pref_f, respectively), i.e.
The loss section in the input.json is
"loss" : {
"start_pref_e": 0.02,
"limit_pref_e": 1,
"start_pref_f": 1000,
"limit_pref_f": 1,
"start_pref_v": 0,
"limit_pref_v": 0
}
The options start_pref_e, limit_pref_e, start_pref_f, limit_pref_f, start_pref_v and limit_pref_v determine the start and limit prefactors of energy, force and virial, respectively.
If one does not want to train with virial, then he/she may set the virial prefactors start_pref_v and limit_pref_v to 0.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Fit spin energy
In this section, we will take $deepmd_source_dir/examples/NiO/se_e2_a/input.json as an example of the input file.
Spin
The construction of the fitting net is give by section spin
"spin" : {
"use_spin": [true, false],
"virtual_len": [0.4],
"spin_norm": [1.2737],
},
use_spin determines whether to turn on the magnetism of the atoms.The index of this option matches option
type_map <model/type_map>.virtual_len specifies the distance between virtual atom and the belonging real atom.
spin_norm gives the magnitude of the magnetic moment for each magnatic atom.
Spin Loss
The spin loss function \(L\) for training energy is given by
where \(L_e\), \(L_{fr}\), \(L_{fm}\) and \(L_v\) denote the loss in energy, atomic force, magnatic force and virial, respectively. \(p_e\), \(p_{fr}\), \(p_{fm}\) and \(p_v\) give the prefactors of the energy, atomic force, magnatic force and virial losses.
The prefectors may not be a constant, rather it changes linearly with the learning rate. Taking the atomic force prefactor for example, at training step \(t\), it is given by
where \(\alpha(t)\) denotes the learning rate at step \(t\). \(p_{fr}^0\) and \(p_{fr}^\infty\) specifies the \(p_f\) at the start of the training and at the limit of \(t \to \infty\) (set by start_pref_fr and limit_pref_f, respectively), i.e.
The loss section in the input.json is
"loss" :{
"type": "ener_spin",
"start_pref_e": 0.02,
"limit_pref_e": 1,
"start_pref_fr": 1000,
"limit_pref_fr": 1.0,
"start_pref_fm": 10000,
"limit_pref_fm": 10.0,
"start_pref_v": 0,
"limit_pref_v": 0,
},
The options start_pref_e, limit_pref_e, start_pref_fr, limit_pref_fm, start_pref_v and limit_pref_v determine the start and limit prefactors of energy, atomic force, magnatic force and virial, respectively.
If one does not want to train with virial, then he/she may set the virial prefactors start_pref_v and limit_pref_v to 0.
Fit tensor like Dipole and Polarizability
Unlike energy, which is a scalar, one may want to fit some high dimensional physical quantity, like dipole (vector) and polarizability (matrix, shorted as polar). Deep Potential has provided different APIs to do this. In this example, we will show you how to train a model to fit a water system. A complete training input script of the examples can be found in
$deepmd_source_dir/examples/water_tensor/dipole/dipole_input.json
$deepmd_source_dir/examples/water_tensor/polar/polar_input.json
The training and validation data are also provided our examples. But note that the data provided along with the examples are of limited amount, and should not be used to train a production model.
Similar to the input.json used in ener mode, training JSON is also divided into model, learning_rate, loss and training. Most keywords remain the same as ener mode, and their meaning can be found here. To fit a tensor, one needs to modify model/fitting_net and loss.
Theory
To represent the first-order tensorial properties (i.e. vector properties), we let the fitting network, denoted by \(\mathcal F_{1}\), output an \(M\)-dimensional vector; then we have the representation,
We let the fitting network \(\mathcal F_{2}\) output an \(M\)-dimensional vector, and the second-order tensorial properties (matrix properties) are formulated as
where \(\mathcal{G}^i\) and \(\mathcal{R}^i\) can be found in se_e2_a. Thus, the tensor fitting network requires the descriptor to have the same or similar form as the DeepPot-SE descriptor. \(\mathcal{F}_1\) and \(\mathcal F_2\) are the neural network functions. The total tensor \(\boldsymbol{T}\) (total dipole \(\boldsymbol{T}^{(1)}\) or total polarizability \(\boldsymbol{T}^{(2)}\)) is the sum of the atomic tensor:
The tensorial models can be used to calculate IR spectrum and Raman spectrum.1
The fitting Network
The fitting_net section tells DP which fitting net to use.
The JSON of dipole type should be provided like
"fitting_net" : {
"type": "dipole",
"sel_type": [0],
"neuron": [100,100,100],
"resnet_dt": true,
"seed": 1,
},
The JSON of polar type should be provided like
"fitting_net" : {
"type": "polar",
"sel_type": [0],
"neuron": [100,100,100],
"resnet_dt": true,
"seed": 1,
},
typespecifies which type of fitting net should be used. It should be eitherdipoleorpolar. Note thatglobal_polarmode in version 1.x is already deprecated and is merged intopolar. To specify whether a system is global or atomic, please see here.sel_typeis a list specifying which type of atoms have the quantity you want to fit. For example, in the water system,sel_typeis[0]since0represents atomO. If left unset, all types of atoms will be fitted.The rest arguments have the same meaning as they do in
enermode.
Loss
DP supports a combinational training of the global system (only a global tensor label, i.e. dipole or polar, is provided in a frame) and atomic system (labels for each atom included in sel_type are provided). In a global system, each frame has just one tensor label. For example, when fitting polar, each frame will just provide a 1 x 9 vector which gives the elements of the polarizability tensor of that frame in order XX, XY, XZ, YX, YY, YZ, XZ, ZY, ZZ. By contrast, in an atomic system, each atom in sel_type has a tensor label. For example, when fitting a dipole, each frame will provide a #sel_atom x 3 matrices, where #sel_atom is the number of atoms whose type are in sel_type.
The loss section tells DP the weight of these two kinds of loss, i.e.
loss = pref * global_loss + pref_atomic * atomic_loss
The loss section should be provided like
"loss" : {
"type": "tensor",
"pref": 1.0,
"pref_atomic": 1.0
},
type should be written as
tensoras a distinction fromenermode.pref and pref_atomic respectively specify the weight of global loss and atomic loss. It can not be left unset. If set to 0, the corresponding label will NOT be included in the training process.
Training Data Preparation
In tensor mode, the identification of the label’s type (global or atomic) is derived from the file name. The global label should be named dipole.npy/raw or polarizability.npy/raw, while the atomic label should be named atomic_dipole.npy/raw or atomic_polarizability.npy/raw. If wrongly named, DP will report an error
ValueError: cannot reshape array of size xxx into shape (xx,xx). This error may occur when your label mismatch it's name, i.e. you might store global tensor in `atomic_tensor.npy` or atomic tensor in `tensor.npy`.
In this case, please check the file name of the label.
Train the Model
The training command is the same as ener mode, i.e.
dp train input.json
The detailed loss can be found in lcurve.out:
# step rmse_val rmse_trn rmse_lc_val rmse_lc_trn rmse_gl_val rmse_gl_trn lr
0 8.34e+00 8.26e+00 8.34e+00 8.26e+00 0.00e+00 0.00e+00 1.0e-02
100 3.51e-02 8.55e-02 0.00e+00 8.55e-02 4.38e-03 0.00e+00 5.0e-03
200 4.77e-02 5.61e-02 0.00e+00 5.61e-02 5.96e-03 0.00e+00 2.5e-03
300 5.68e-02 1.47e-02 0.00e+00 0.00e+00 7.10e-03 1.84e-03 1.3e-03
400 3.73e-02 3.48e-02 1.99e-02 0.00e+00 2.18e-03 4.35e-03 6.3e-04
500 2.77e-02 5.82e-02 1.08e-02 5.82e-02 2.11e-03 0.00e+00 3.2e-04
600 2.81e-02 5.43e-02 2.01e-02 0.00e+00 1.01e-03 6.79e-03 1.6e-04
700 2.97e-02 3.28e-02 2.03e-02 0.00e+00 1.17e-03 4.10e-03 7.9e-05
800 2.25e-02 6.19e-02 9.05e-03 0.00e+00 1.68e-03 7.74e-03 4.0e-05
900 3.18e-02 5.54e-02 9.93e-03 5.54e-02 2.74e-03 0.00e+00 2.0e-05
1000 2.63e-02 5.02e-02 1.02e-02 5.02e-02 2.01e-03 0.00e+00 1.0e-05
1100 3.27e-02 5.89e-02 2.13e-02 5.89e-02 1.43e-03 0.00e+00 5.0e-06
1200 2.85e-02 2.42e-02 2.85e-02 0.00e+00 0.00e+00 3.02e-03 2.5e-06
1300 3.47e-02 5.71e-02 1.07e-02 5.71e-02 3.00e-03 0.00e+00 1.3e-06
1400 3.13e-02 5.76e-02 3.13e-02 5.76e-02 0.00e+00 0.00e+00 6.3e-07
1500 3.34e-02 1.11e-02 2.09e-02 0.00e+00 1.57e-03 1.39e-03 3.2e-07
1600 3.11e-02 5.64e-02 3.11e-02 5.64e-02 0.00e+00 0.00e+00 1.6e-07
1700 2.97e-02 5.05e-02 2.97e-02 5.05e-02 0.00e+00 0.00e+00 7.9e-08
1800 2.64e-02 7.70e-02 1.09e-02 0.00e+00 1.94e-03 9.62e-03 4.0e-08
1900 3.28e-02 2.56e-02 3.28e-02 0.00e+00 0.00e+00 3.20e-03 2.0e-08
2000 2.59e-02 5.71e-02 1.03e-02 5.71e-02 1.94e-03 0.00e+00 1.0e-08
One may notice that in each step, some of the local loss and global loss will be 0.0. This is because our training data and validation data consist of the global system and atomic system, i.e.
--training_data
>atomic_system
>global_system
--validation_data
>atomic_system
>global_system
During training, at each step when the lcurve.out is printed, the system used for evaluating the training (validation) error may be either with only global or only atomic labels, thus the corresponding atomic or global errors are missing and are printed as zeros.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Fit electronic density of states (DOS)
Here we present an API to DeepDOS model, which can be used to fit electronic density of state (DOS) (which is a vector).
See the PRB paper for details.
In this example, we will show you how to train a model to fit a silicon system. A complete training input script of the examples can be found in
$deepmd_source_dir/examples/dos/input.json
The training and validation data are also provided our examples. But note that the data provided along with the examples are of limited amount, and should not be used to train a production model.
Similar to the input.json used in ener mode, training JSON is also divided into model, learning_rate, loss and training. Most keywords remain the same as ener mode, and their meaning can be found here. To fit the dos, one needs to modify model/fitting_net and loss.
The fitting Network
The fitting_net section tells DP which fitting net to use.
The JSON of dos type should be provided like
"fitting_net" : {
"type": "dos",
"numb_dos": 250,
"sel_type": [0],
"neuron": [120,120,120],
"resnet_dt": true,
"fparam": 0,
"seed": 1,
},
typespecifies which type of fitting net should be used. It should bedos.numb_dosspecifies the length of output vector (density of states), which the same as theNEDOSset in VASP software, this argument defines the output length of the neural network. We note that the length ofdosprovided in training set should be the same.The rest arguments have the same meaning as they do in
enermode.
Loss
DeepDOS supports trainings of the global system (a global dos label is provided in a frame) or atomic system (atomic labels atom_dos is provided for each atom in a frame). In a global system, each frame has just one dos label. For example, when fitting dos, each frame will just provide a 1 x numb_dos vector which gives the total electronic density of states. By contrast, in an atomic system, each atom in has a atom_dos label. For example, when fitting the site-projected electronic density of states, each frame will provide a natom x numb_dos matrices,
The loss section tells DP the weight of these two kinds of loss, i.e.
loss = pref * global_loss + pref_atomic * atomic_loss
The loss section should be provided like
"loss" : {
"type": "dos",
"start_pref_dos": 0.0,
"limit_pref_dos": 0.0,
"start_pref_cdf": 0.0,
"limit_pref_cdf": 0.0,
"start_pref_ados": 1.0,
"limit_pref_ados": 1.0,
"start_pref_acdf": 0.0,
"limit_pref_acdf": 0.0
},
type should be written as
dosas a distinction fromenermode.pref_dosandpref_ados, respectively specify the weight of global and atomic loss. If set to 0, the corresponding label will not be included in the training process.We also provides a combination training of vector and its cumulative distribution function
cdf, which can be defined as
Training Data Preparation
The global label should be named dos.npy/raw, while the atomic label should be named atomic_dos.npy/raw. If wrongly named, DP will report an error.
To prepare the data, we recommend shifting the DOS data by the Fermi level.
Train the Model
The training command is the same as ener mode, i.e.
dp train input.json
The detailed loss can be found in lcurve.out:
# step rmse_trn rmse_ados_trn rmse_ados_lr
0 1.11e+00 1.11e+00 1.0e-03
100 5.00e-02 5.00e-02 1.0e-03
200 4.70e-02 4.70e-02 1.0e-03
300 6.45e-02 6.45e-02 1.0e-03
400 3.39e-02 3.39e-02 1.0e-03
500 4.60e-02 4.60e-02 1.0e-03
600 3.98e-02 3.98e-02 1.0e-03
700 9.50e-02 9.50e-02 1.0e-03
800 5.49e-02 5.49e-02 1.0e-03
900 5.57e-02 5.57e-02 1.0e-03
1000 3.73e-02 3.73e-02 1.0e-03
1100 4.33e-02 4.33e-02 1.0e-03
1200 3.27e-02 3.27e-02 1.0e-03
1300 3.68e-02 3.68e-02 1.0e-03
1400 3.09e-02 3.09e-02 1.0e-03
1500 3.42e-02 3.42e-02 1.0e-03
1600 5.62e-02 5.62e-02 1.0e-03
1700 6.12e-02 6.12e-02 1.0e-03
1800 4.10e-02 4.10e-02 1.0e-03
1900 5.30e-02 5.30e-02 1.0e-03
2000 3.85e-02 3.85e-02 1.0e-03
Test the Model
In this earlier version, we can use dp test to infer the electronic density of state for given frames.
$DP freeze -o frozen_model.pb
$DP test -m frozen_model.pb -s ../data/111/$k -d ${output_prefix} -a -n 100
if dp test -d ${output_prefix} -a is specified, the predicted DOS and atomic DOS for each frame is output in the working directory
${output_prefix}.ados.out.0 ${output_prefix}.ados.out.1 ${output_prefix}.ados.out.2 ${output_prefix}.ados.out.3
${output_prefix}.dos.out.0 ${output_prefix}.dos.out.1 ${output_prefix}.dos.out.2 ${output_prefix}.dos.out.3
for *.dos.out.*, it contains matrix with shape of (2, numb_dos), for *.ados.out.*, it contains matrix with shape of (2, natom x numb_dos),
# frame - 0: data_dos pred_dos
0.000000000000000000e+00 1.963193264917645342e-03
0.000000000000000000e+00 1.178440836781313727e-03
0.000000000000000000e+00 1.441258071790407769e-04
0.000000000000000000e+00 1.787297933314058174e-03
0.000000000000000000e+00 1.901603280243024940e-03
0.000000000000000000e+00 2.279848925571981155e-03
0.000000000000000000e+00 2.149355854688561607e-03
0.000000000000000000e+00 1.829848459515726056e-03
0.000000000000000000e+00 1.905156512419792225e-03
Type embedding approach
We generate specific a type embedding vector for each atom type so that we can share one descriptor embedding net and one fitting net in total, which decline training complexity largely.
The training input script is similar to that of se_e2_a, but different by adding the type_embedding section.
Theory
Usually, when the type embedding approach is not enabled, for a system with multiple chemical species (\(|\{\alpha_i\}| > 1\)), parameters of the embedding network \(\mathcal{N}_{e,\{2,3\}}\) are as follows chemical-species-wise:
Thus, there will be \(N_t^2\) or \(N_t\) embedding networks where \(N_t\) is the number of chemical species. To improve the performance of matrix operations, \(n(i)\) is divided into blocks of different chemical species. Each matrix with a dimension of \(N_c\) is divided into corresponding blocks, and each block is padded to \(N_c^{\alpha_j}\) separately. The limitation of this approach is that when there are large numbers of chemical species, the number of embedding networks will increase, requiring large memory and decreasing computing efficiency.
Similar to the embedding networks, if the type embedding approach is not used, the fitting network parameters are chemical-species-wise, and there are \(N_t\) sets of fitting network parameters. For performance, atoms are sorted by their chemical species \(\alpha_i\) in advance. Take an example, the atomic energy \(E_i\) is represented as follows:
To reduce the number of NN parameters and improve computing efficiency when there are large numbers of chemical species, the type embedding \(\mathcal{A}\) is introduced, represented as a NN function \(\mathcal{N}_t\) of the atomic type \(\alpha\):
where \(\alpha_i\) is converted to a one-hot vector representing the chemical species before feeding to the NN. The type embeddings of central and neighboring atoms \(\mathcal{A}^i\) and \(\mathcal{A}^j\) are added as an extra input of the embedding network \(\mathcal{N}_{e,\{2,3\}}\):
In fitting networks, the type embedding is inserted into the input of the fitting networks:
In this way, all chemical species share the same network parameters through the type embedding.1
Instructions
The model defines how the model is constructed, adding a section of type embedding net:
"model": {
"type_map": ["O", "H"],
"type_embedding":{
...
},
"descriptor" :{
...
},
"fitting_net" : {
...
}
}
The model will automatically apply the type embedding approach and generate type embedding vectors. If the type embedding vector is detected, the descriptor and fitting net would take it as a part of the input.
The construction of type embedding net is given by type_embedding. An example of type_embedding is provided as follows
"type_embedding":{
"neuron": [2, 4, 8],
"resnet_dt": false,
"seed": 1
}
The neuron specifies the size of the type embedding net. From left to right the members denote the sizes of each hidden layer from the input end to the output end, respectively. It takes a one-hot vector as input and output dimension equals to the last dimension of the neuron list. If the outer layer is twice the size of the inner layer, then the inner layer is copied and concatenated, then a ResNet architecture is built between them.
If the option resnet_dt is set to
true, then a timestep is used in the ResNet.seed gives the random seed that is used to generate random numbers when initializing the model parameters.
A complete training input script of this example can be found in the directory.
$deepmd_source_dir/examples/water/se_e2_a_tebd/input.json
See here for further explanation of type embedding.
Note
You can’t apply the compression method while using the atom type embedding.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Descriptor "se_a_mask"
Descriptor se_a_mask is a concise implementation of the descriptor se_e2_a, but functions slightly differently. se_a_mask is specially designed for DP/MM simulations where the number of atoms in DP regions is dynamically changed in simulations.
Therefore, the descriptor se_a_mask is not supported for training with PBC systems for simplicity. Besides, to make the output shape of the descriptor matrix consistent, the input coordinates are padded with virtual particle coordinates to the maximum number of atoms (specified with sel in the descriptor setting) in the system. The real/virtual sign of the atoms is specified with the aparam.npy ( [ nframes * natoms ] ) file in the input systems set directory. The aparam.npy can also be seen as the mask of the atoms in the system, which is also the origin of the name se_a_mask.
In this example, we will train a DP Mask model for zinc protein interactions. The input systems are the collection of zinc and its coordinates residues. A sample input system that contains 2 frames is included in the directory.
$deepmd_source_dir/examples/zinc_protein/data_dp_mask
A complete training input script of this example can be found in the directory.
$deepmd_source_dir/examples/zinc_protein/zinc_se_a_mask.json
The construction of the descriptor is given by section descriptor. An example of the descriptor is provided as follows
"descriptor" :{
"type": "se_a_mask",
"sel": [36, 16, 24, 64, 6, 1],
"neuron": [25, 50, 100],
"axis_neuron": 16,
"type_one_side": false,
"resnet_dt": false,
"seed": 1
}
The type of the descriptor is set to
"se_a_mask".sel gives the maximum number of atoms in input coordinates. It is a list, the length of which is the same as the number of atom types in the system, and
sel[i]denotes the maximum number of atoms with typei.The neuron specifies the size of the embedding net. From left to right the members denote the sizes of each hidden layer from the input end to the output end, respectively. If the outer layer is twice the size of the inner layer, then the inner layer is copied and concatenated, then a ResNet architecture is built between them.
The axis_neuron specifies the size of the submatrix of the embedding matrix, the axis matrix as explained in the DeepPot-SE paper
If the option type_one_side is set to
true, the embedding network parameters vary by types of neighbor atoms only, so there will be \(N_\text{types}\) sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be \(N_\text{types}^2\) sets of embedding network parameters.If the option resnet_dt is set to
true, then a timestep is used in the ResNet.seed gives the random seed that is used to generate random numbers when initializing the model parameters.
To make the aparam.npy used for descriptor se_a_mask, two variables in fitting_net section are needed.
"fitting_net" :{
"neuron": [240, 240, 240],
"resnet_dt": true,
"seed": 1,
"numb_aparam": 1,
"use_aparam_as_mask": true
}
neuron,resnet_dtandseedare the same as the fitting_net section for fitting energy.numb_aparam gives the dimesion of the
aparam.npyfile. In this example, it is set to 1 and stores the real/virtual sign of the atoms. For real/virtual atoms, the corresponding sign inaparam.npyis set to 1/0.use_aparam_as_mask is set to
trueto use theaparam.npyas the mask of the atoms in the descriptorse_a_mask.
Finally, to make a reasonable fitting task with se_a_mask descriptor for DP/MM simulations, the loss function with se_a_mask is designed to include the atomic forces difference in specific atoms of the input particles only. More details about the selection of the specific atoms can be found in paper [DP/MM](left to be filled). Thus, atom_pref.npy ( [ nframes * natoms ] ) is required as the indicator of the specific atoms in the input particles. And the loss section in the training input script should be set as follows.
"loss": {
"type": "ener",
"start_pref_e": 0.0,
"limit_pref_e": 0.0,
"start_pref_f": 0.0,
"limit_pref_f": 0.0,
"start_pref_pf": 1.0,
"limit_pref_pf": 1.0,
"_comment": " that's all"
}
Deep potential long-range (DPLR)
Notice: The interfaces of DPLR are not stable and subject to change
The method of DPLR is described in this paper. One is recommended to read the paper before using the DPLR.
In the following, we take the DPLR model for example to introduce the training and LAMMPS simulation with the DPLR model. The DPLR model is trained in two steps.
Theory
The Deep Potential Long Range (DPLR) model adds the electrostatic energy to the total energy:
where \(E_{\text{DP}}\) is the short-range contribution constructed as the standard energy model that is fitted against \((E^\ast-E_{\text{ele}})\). \(E_{\text{ele}}\) is the electrostatic energy introduced by a group of Gaussian distributions that is an approximation of the electronic structure of the system, and is calculated in Fourier space by
where \(\beta\) is a freely tunable parameter that controls the spread of the Gaussians. \(L\) is the cutoff in Fourier space and \(S(m)\), the structure factor, is given by
where \(\imath = \sqrt{-1}\) denotes the imaginary unit, \(\boldsymbol r_i\) indicates ion coordinates, \(q_i\) is the charge of the ion \(i\), and \(W_n\) is the \(n\)-th Wannier centroid (WC) which can be obtained from a separated dipole model. It can be proved that the error in the electrostatic energy introduced by the Gaussian approximations is dominated by a summation of dipole-quadrupole interactions that decay as \(r^{-4}\), where \(r\) is the distance between the dipole and quadrupole.1
Train a deep Wannier model for Wannier centroids
We use the deep Wannier model (DW) to represent the relative position of the Wannier centroid (WC) with the atom with which it is associated. One may consult the introduction of the dipole model for a detailed introduction. An example input wc.json and a small dataset data for tutorial purposes can be found in
$deepmd_source_dir/examples/water/dplr/train/
It is noted that the tutorial dataset is not enough for training a productive model. Two settings make the training input script different from an energy training input:
"fitting_net": {
"type": "dipole",
"dipole_type": [0],
"neuron": [128, 128, 128],
"seed": 1
},
The type of fitting is set to dipole. The dipole is associated with type 0 atoms (oxygens), by the setting "dipole_type": [0]. What we trained is the displacement of the WC from the corresponding oxygen atom. It shares the same training input as the atomic dipole because both are 3-dimensional vectors defined on atoms. The loss section is provided as follows
"loss": {
"type": "tensor",
"pref": 0.0,
"pref_atomic": 1.0
},
so that the atomic dipole is trained as labels. Note that the NumPy compressed file atomic_dipole.npy should be provided in each dataset.
The training and freezing can be started from the example directory by
dp train dw.json && dp freeze -o dw.pb
Train the DPLR model
The training of the DPLR model is very similar to the standard short-range DP models. An example input script can be found in the example directory. The following section is introduced to compute the long-range energy contribution of the DPLR model, and modify the short-range DP model by this part.
"modifier": {
"type": "dipole_charge",
"model_name": "dw.pb",
"model_charge_map": [-8],
"sys_charge_map": [6, 1],
"ewald_h": 1.00,
"ewald_beta": 0.40
},
The model_name specifies which DW model is used to predict the position of WCs. model_charge_map gives the amount of charge assigned to WCs. sys_charge_map provides the nuclear charge of oxygen (type 0) and hydrogen (type 1) atoms. ewald_beta (unit \(\text{Å}^{-1}\)) gives the spread parameter controls the spread of Gaussian charges, and ewald_h (unit Å) assigns the grid size of Fourier transformation. The DPLR model can be trained and frozen by (from the example directory)
dp train ener.json && dp freeze -o ener.pb
Molecular dynamics simulation with DPLR
In MD simulations, the long-range part of the DPLR is calculated by the LAMMPS kspace support. Then the long-range interaction is back-propagated to atoms by DeePMD-kit. This setup is commonly used in classical molecular dynamics simulations as the “virtual site”. Unfortunately, LAMMPS does not natively support virtual sites, so we have to hack the LAMMPS code, which makes the input configuration and script a little wired.
An example of an input configuration file and script can be found in
$deepmd_source_dir/examples/water/dplr/lmp/
We use atom_style full for DPLR simulations. the coordinates of the WCs are explicitly written in the configuration file. Moreover, a virtual bond is established between the oxygens and the WCs to indicate they are associated together. The configuration file containing 128 H2O molecules is thus written as
512 atoms
3 atom types
128 bonds
1 bond types
0 16.421037674 xlo xhi
0 16.421037674 ylo yhi
0 16.421037674 zlo zhi
0 0 0 xy xz yz
Masses
1 16
2 2
3 16
Atoms
1 1 1 6 8.4960699081e+00 7.5073699951e+00 9.6371297836e+00
2 2 1 6 4.0597701073e+00 6.8156299591e+00 1.2051420212e+01
...
385 1 3 -8 8.4960699081e+00 7.5073699951e+00 9.6371297836e+00
386 2 3 -8 4.0597701073e+00 6.8156299591e+00 1.2051420212e+01
...
Bonds
1 1 1 385
2 1 2 386
...
The oxygens and hydrogens are assigned with atom types 1 and 2 (corresponding to training atom types 0 and 1), respectively. The WCs are assigned with atom type 3. We want to simulate heavy water so the mass of hydrogens is set to 2.
An example input script is provided in
$deepmd_source_dir/examples/water/dplr/lmp/in.lammps
Here are some explanations
# groups of real and virtual atoms
group real_atom type 1 2
group virtual_atom type 3
# bond between real and its corresponding virtual site should be given
# to setup a map between real and virtual atoms. However, no real
# bonded interaction is applied, thus bond_sytle "zero" is used.
pair_style deepmd ener.pb
pair_coeff * *
bond_style zero
bond_coeff *
special_bonds lj/coul 1 1 1 angle no
Type 1 and 2 (O and H) are real_atoms, while type 3 (WCs) are virtual_atoms. The model file ener.pb stores both the DW and DPLR models, so the position of WCs and the energy can be inferred from it. A virtual bond type is specified by bond_style zero. The special_bonds command switches off the exclusion of intramolecular interactions.
# kspace_style "pppm/dplr" should be used. in addition the
# gewald(1/distance) should be set the same as that used in
# training. Currently only ik differentiation is supported.
kspace_style pppm/dplr 1e-5
kspace_modify gewald ${BETA} diff ik mesh ${KMESH} ${KMESH} ${KMESH}
The long-range part is calculated by the kspace support of LAMMPS. The kspace_style pppm/dplr is required. The spread parameter set by variable BETA should be set the same as that used in training. The KMESH should be set dense enough so the long-range calculation is converged.
fix dplr command
Syntax
fix ID group-ID style_name keyword value ...
ID, group-ID are documented in :doc:
fix <fix>commandstyle_name = dplr
three or more keyword/value pairs may be appended
keyword = *model* or *type_associate* or *bond_type* or *efield*
*model* value = name
name = name of DPLR model file (e.g. frozen_model.pb) (not DW model)
*type_associate* values = NR1 NW1 NR2 NW2 ...
NRi = type of real atom in i-th (real atom, Wannier centroid) pair
NWi = type of Wannier in i-th (real atom, Wannier centroid) pair
*bond_type* values = NB1 NB2 ...
NBi = bond type of i-th (real atom, Wannier centroid) pair
*efield* (optional) values = Ex Ey Ez
Ex/Ey/Ez = electric field along x/y/z direction
Examples
# "fix dplr" set the position of the virtual atom, and spread the
# electrostatic interaction asserting on the virtual atom to the real
# atoms. "type_associate" associates the real atom type its
# corresponding virtual atom type. "bond_type" gives the type of the
# bond between the real and virtual atoms.
fix 0 all dplr model ener.pb type_associate 1 3 bond_type 1
fix_modify 0 virial yes
The fix command dplr calculates the position of WCs by the DW model and back-propagates the long-range interaction on virtual atoms to real toms. The atom names specified in pair_style deepmd will be used to determine elements. If it is not set, the training parameter type_map will be mapped to LAMMPS atom types.
To use a time-dependent electric field, LAMMPS’s variable feature can be utilized:
variable EFIELD_Z equal 2*sin(2*PI*time/0.006)
fix 0 all dplr model ener.pb type_associate 1 3 bond_type 1 efield 0 0 v_EFIELD_Z
fix_modify 0 energy yes virial yes
The efield feature of fix dplr behaves similarly to LAMMPS’s fix efield. Note that the atomic energy or potential in fix efield is not yet supported in fix dplr. For a detailed description on how a time-dependent variable can be defined, refer to LAMMPS’s document of variable.
# compute the temperature of real atoms, excluding virtual atom contribution
compute real_temp real_atom temp
compute real_press all pressure real_temp
fix 1 real_atom nvt temp ${TEMP} ${TEMP} ${TAU_T}
fix_modify 1 temp real_temp
The temperature of the system should be computed from the real atoms. The kinetic contribution in the pressure tensor is also computed from the real atoms. The thermostat is applied to only real atoms. The computed temperature and pressure of real atoms can be accessed by, e.g.
fix thermo_print all print ${THERMO_FREQ} "$(step) $(pe) $(ke) $(etotal) $(enthalpy) $(c_real_temp) $(c_real_press) $(vol) $(c_real_press[1]) $(c_real_press[2]) $(c_real_press[3])" append thermo.out screen no title "# step pe ke etotal enthalpy temp press vol pxx pyy pzz"
The LAMMPS simulation can be started from the example directory by
lmp -i in.lammps
If LAMMPS complains that no model file ener.pb exists, it can be copied from the training example directory.
The MD simulation lasts for only 20 steps. If one runs a longer simulation, it will blow up, because the model is trained with a very limited dataset for very short training steps, thus is of poor quality.
Another restriction that should be noted is that the energies printed at the zero steps are not correct. This is because at the zero steps the position of the WC has not been updated with the DW model. The energies printed in later steps are correct.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Deep Potential - Range Correction (DPRc)
Deep Potential - Range Correction (DPRc) is designed to combine with QM/MM method, and corrects energies from a low-level QM/MM method to a high-level QM/MM method:
Theory
Deep Potential - Range Correction (DPRc) was initially designed to correct the potential energy from a fast, linear-scaling low-level semiempirical QM/MM theory to a high-level ‘’ab initio’’ QM/MM theory in a range-correction way to quantitatively correct short and mid-range non-bonded interactions leveraging the non-bonded lists routinely used in molecular dynamics simulations using molecular mechanical force fields such as AMBER. In this way, long-ranged electrostatic interactions can be modeled efficiently using the particle mesh Ewald method or its extensions for multipolar and QM/MM potentials. In a DPRc model, the switch function is modified to disable MM-MM interaction:
where \(s_\text{DPRc}(r_{ij})\) is the new switch function and \(s(r_{ij})\) is the old one. This ensures the forces between MM atoms are zero, i.e.
The fitting network is revised to remove energy bias from MM atoms:
where \(\mathbf{0}\) is a zero matrix. It is worth mentioning that usage of DPRc is not limited to its initial design for QM/MM correction and can be expanded to any similar interaction.1
See the JCTC paper for details.
Training data
Instead the normal ab initio data, one needs to provide the correction from a low-level QM/MM method to a high-level QM/MM method:
Two levels of data use the same MM method, so \(E_\text{MM}\) is eliminated.
Training the DPRc model
In a DPRc model, QM atoms and MM atoms have different atom types. Assuming we have 4 QM atom types (C, H, O, P) and 2 MM atom types (HW, OW):
"type_map": ["C", "H", "HW", "O", "OW", "P"]
As described in the paper, the DPRc model only corrects \(E_\text{QM}\) and \(E_\text{QM/MM}\) within the cutoff, so we use a hybrid descriptor to describe them separatedly:
"descriptor" :{
"type": "hybrid",
"list" : [
{
"type": "se_a_ebd_v2",
"sel": [6, 11, 0, 6, 0, 1],
"rcut_smth": 1.00,
"rcut": 9.00,
"neuron": [12, 25, 50],
"exclude_types": [[2, 2], [2, 4], [4, 4], [0, 2], [0, 4], [1, 2], [1, 4], [3, 2], [3, 4], [5, 2], [5, 4]],
"axis_neuron": 12,
"_comment": " QM/QM interaction"
},
{
"type": "se_a_ebd_v2",
"sel": [6, 11, 100, 6, 50, 1],
"rcut_smth": 0.50,
"rcut": 6.00,
"neuron": [12, 25, 50],
"exclude_types": [[0, 0], [0, 1], [0, 3], [0, 5], [1, 1], [1, 3], [1, 5], [3, 3], [3, 5], [5, 5], [2, 2], [2, 4], [4, 4]],
"axis_neuron": 12,
"set_davg_zero": true,
"_comment": " QM/MM interaction"
}
]
}
exclude_types can be generated by the following Python script:
from itertools import combinations_with_replacement, product
qm = (0, 1, 3, 5)
mm = (2, 4)
print(
"QM/QM:",
list(map(list, list(combinations_with_replacement(mm, 2)) + list(product(qm, mm)))),
)
print(
"QM/MM:",
list(
map(
list,
list(combinations_with_replacement(qm, 2))
+ list(combinations_with_replacement(mm, 2)),
)
),
)
Also, DPRc assumes MM atom energies (atom_ener) are zero:
"fitting_net": {
"neuron": [240, 240, 240],
"resnet_dt": true,
"atom_ener": [null, null, 0.0, null, 0.0, null]
}
Note that atom_ener only works when descriptor/set_davg_zero of the QM/MM part is true.
Run MD simulations
The DPRc model has the best practices with the AMBER QM/MM module. An example is given by GitLab RutgersLBSR/AmberDPRc. In theory, DPRc is able to be used with any QM/MM package, as long as the DeePMD-kit package accepts QM atoms and MM atoms within the cutoff range and returns energies and forces.
Pairwise DPRc
If one wants to correct from a low-level method into a full DFT level, and the system is too large to do full DFT calculation, one may try the experimental pairwise DPRc model. In a pairwise DPRc model, the total energy is divided into QM internal energy and the sum of QM/MM energy for each MM residue \(l\):
In this way, the interaction between the QM region and each MM fragmentation can be computed and trained separately. Thus, the pairwise DPRc model is divided into two sub-DPRc models. qm_model is for the QM internal interaction and qmmm_model is for the QM/MM interaction. The configuration for these two models is similar to the non-pairwise DPRc model. It is noted that the se_atten descriptor should be used, as it is the only descriptor to support the mixed type.
{
"model": {
"type": "pairwise_dprc",
"type_map": ["C", "P", "O", "H", "OW", "HW"],
"type_embedding": {
"neuron": [8],
"precision": "float32"
},
"qm_model": {
"descriptor": {
"type": "se_atten_v2",
"sel": 24,
"rcut_smth": 0.5,
"rcut": 9.0,
"attn_layer": 0,
"neuron": [25, 50, 100],
"resnet_dt": false,
"axis_neuron": 12,
"precision": "float32",
"seed": 1
},
"fitting_net": {
"type": "ener",
"neuron": [240, 240, 240],
"resnet_dt": true,
"precision": "float32",
"atom_ener": [null, null, null, null, 0.0, 0.0],
"seed": 1
}
},
"qmmm_model": {
"descriptor": {
"type": "se_atten_v2",
"sel": 27,
"rcut_smth": 0.5,
"rcut": 6.0,
"attn_layer": 0,
"neuron": [25, 50, 100],
"resnet_dt": false,
"axis_neuron": 12,
"set_davg_zero": true,
"exclude_types": [
[0, 0],
[0, 1],
[0, 2],
[0, 3],
[1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 3],
[3, 3],
[4, 4],
[4, 5],
[5, 5]
],
"precision": "float32",
"seed": 1
},
"fitting_net": {
"type": "ener",
"neuron": [240, 240, 240],
"resnet_dt": true,
"seed": 1,
"precision": "float32",
"atom_ener": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
}
}
}
}
The pairwise model needs information for MM residues. The model uses aparam with the shape of nframes x natoms to get the residue index. The QM residue should always use 0 as the index. For example, 0 0 0 1 1 1 2 2 2 means these 9 atoms are grouped into one QM residue and two MM residues.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Linear model
One can linearly combine existing models with arbitrary coefficients:
"model": {
"type": "linear_ener",
"models": [
{
"type": "frozen",
"model_file": "model0.pb"
},
{
"type": "frozen",
"model_file": "model1.pb"
}
],
"weights": [0.5, 0.5]
},
weights can be a list of floats, mean, or sum.
To obtain the model, one needs to execute dp train to do a zero-step training with numb_steps set to 0, and then freeze the model with dp freeze.
Interpolation or combination with a pairwise potential
Theory
In applications like the radiation damage simulation, the interatomic distance may become too close, so that the DFT calculations fail. In such cases, the DP model that is an approximation of the DFT potential energy surface is usually replaced by an empirical potential, like the Ziegler-Biersack-Littmark (ZBL) screened nuclear repulsion potential in the radiation damage simulations. The DeePMD-kit package supports the interpolation between DP and an empirical pairwise potential
where the \(w_i\) is the interpolation weight and the \(E_i^{\mathrm{pair}} \) is the atomic contribution due to the pairwise potential \(u^{\mathrm{pair}}(r)\), i.e.
The interpolation weight \(w_i\) is defined by
where \(u_i = (\sigma_i - r_a ) / (r_b - r_a)\). \(E_i^0\) is the atom energy bias. In the range \([r_a, r_b]\), the DP model smoothly switched off and the pairwise potential smoothly switched on from \(r_b\) to \(r_a\). The \(\sigma_i\) is the softmin of the distance between atom \(i\) and its neighbors,
where the scale \(\alpha_s\) is a tunable scale of the interatomic distance \(r_{ij}\). The pairwise potential \(u^{\textrm{pair}}(r)\) is defined by a user-defined table that provides the value of \(u^{\textrm{pair}}\) on an evenly discretized grid from 0 to the cutoff distance.1
DeePMD-kit also supports combination with a pairwise potential:
Table file
The table file should be a text file that can be read by numpy.loadtxt(). The first column is the distance between two atoms, where upper range should be larger than the cutoff radius. Other columns are two-body interaction energies for pairs of certain types, in the order of Type_0-Type_0, Type_0-Type_1, …, Type_0-Type_N, Type_1-Type_1, …, Type_1-Type_N, …, and Type_N-Type_N.
The interaction should be smooth at the cut-off distance.
Interpolation with a short-range pairwise potential
"model": {
"use_srtab": "H2O_tab_potential.txt",
"smin_alpha": 0.1,
"sw_rmin": 0.8,
"sw_rmax": 1.0,
"_comment": "Below uses a normal DP model"
}
sw_rmin and sw_rmax must be smaller than the cutoff radius of the DP model.
Combination with a pairwise potential
To combine with a pairwise potential, use the linear model:
"model": {
"type": "linear_ener",
"weights": "sum",
"models": [
{
"_comment": "Here uses a normal DP model"
},
{
"type": "pairtab",
"tab_file": "dftd3.txt",
"rcut": 10.0,
"sel": 534
}
]
}
The rcut can be larger than that of the DP model.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Training
Train a model
Several examples of training can be found in the examples directory:
$ cd $deepmd_source_dir/examples/water/se_e2_a/
After switching to that directory, the training can be invoked by
$ dp train input.json
where input.json is the name of the input script.
By default, the verbosity level of the DeePMD-kit is INFO, one may see a lot of important information on the code and environment showing on the screen. Among them two pieces of information regarding data systems are worth special notice.
DEEPMD INFO ---Summary of DataSystem: training -----------------------------------------------
DEEPMD INFO found 3 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../data_water/data_0/ 192 1 80 0.250 T
DEEPMD INFO ../data_water/data_1/ 192 1 160 0.500 T
DEEPMD INFO ../data_water/data_2/ 192 1 80 0.250 T
DEEPMD INFO --------------------------------------------------------------------------------------
DEEPMD INFO ---Summary of DataSystem: validation -----------------------------------------------
DEEPMD INFO found 1 system(s):
DEEPMD INFO system natoms bch_sz n_bch prob pbc
DEEPMD INFO ../data_water/data_3 192 1 80 1.000 T
DEEPMD INFO --------------------------------------------------------------------------------------
The DeePMD-kit prints detailed information on the training and validation data sets. The data sets are defined by training_data and validation_data defined in the training section of the input script. The training data set is composed of three data systems, while the validation data set is composed by one data system. The number of atoms, batch size, the number of batches in the system and the probability of using the system are all shown on the screen. The last column presents if the periodic boundary condition is assumed for the system.
During the training, the error of the model is tested every disp_freq training steps with the batch used to train the model and with numb_btch batches from the validating data. The training error and validation error are printed correspondingly in the file disp_file (default is lcurve.out). The batch size can be set in the input script by the key batch_size in the corresponding sections for the training and validation data set. An example of the output
# step rmse_val rmse_trn rmse_e_val rmse_e_trn rmse_f_val rmse_f_trn lr
0 3.33e+01 3.41e+01 1.03e+01 1.03e+01 8.39e-01 8.72e-01 1.0e-03
100 2.57e+01 2.56e+01 1.87e+00 1.88e+00 8.03e-01 8.02e-01 1.0e-03
200 2.45e+01 2.56e+01 2.26e-01 2.21e-01 7.73e-01 8.10e-01 1.0e-03
300 1.62e+01 1.66e+01 5.01e-02 4.46e-02 5.11e-01 5.26e-01 1.0e-03
400 1.36e+01 1.32e+01 1.07e-02 2.07e-03 4.29e-01 4.19e-01 1.0e-03
500 1.07e+01 1.05e+01 2.45e-03 4.11e-03 3.38e-01 3.31e-01 1.0e-03
The file contains 8 columns, from left to right, which are the training step, the validation loss, training loss, root mean square (RMS) validation error of energy, RMS training error of energy, RMS validation error of force, RMS training error of force and the learning rate. The RMS error (RMSE) of the energy is normalized by the number of atoms in the system. One can visualize this file with a simple Python script:
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt("lcurve.out", names=True)
for name in data.dtype.names[1:-1]:
plt.plot(data["step"], data[name], label=name)
plt.legend()
plt.xlabel("Step")
plt.ylabel("Loss")
plt.xscale("symlog")
plt.yscale("log")
plt.grid()
plt.show()
Checkpoints will be written to files with the prefix save_ckpt every save_freq training steps.
Warning
It is warned that the example water data (in folder examples/water/data) is of very limited amount, is provided only for testing purposes, and should not be used to train a production model.
Advanced options
In this section, we will take $deepmd_source_dir/examples/water/se_e2_a/input.json as an example of the input file.
Learning rate
Theory
The learning rate \(\gamma\) decays exponentially:
where \(\tau \in \mathbb{N}\) is the index of the training step, \(\gamma^0 \in \mathbb{R}\) is the learning rate at the first step, and the decay rate \(r\) is given by
where \(\tau^{\text{stop}} \in \mathbb{N}\), \(\gamma^{\text{stop}} \in \mathbb{R}\), and \(s \in \mathbb{N}\) are the stopping step, the stopping learning rate, and the decay steps, respectively, all of which are hyperparameters provided in advance. 1
Instructions
The learning_rate section in input.json is given as follows
"learning_rate" :{
"type": "exp",
"start_lr": 0.001,
"stop_lr": 3.51e-8,
"decay_steps": 5000,
"_comment": "that's all"
}
start_lr gives the learning rate at the beginning of the training.
stop_lr gives the learning rate at the end of the training. It should be small enough to ensure that the network parameters satisfactorily converge.
During the training, the learning rate decays exponentially from start_lr to stop_lr following the formula:
lr(t) = start_lr * decay_rate ^ ( t / decay_steps )
Training parameters
Other training parameters are given in the training section.
"training": {
"training_data": {
"systems": ["../data_water/data_0/", "../data_water/data_1/", "../data_water/data_2/"],
"batch_size": "auto"
},
"validation_data":{
"systems": ["../data_water/data_3"],
"batch_size": 1,
"numb_btch": 3
},
"mixed_precision": {
"output_prec": "float32",
"compute_prec": "float16"
},
"numb_steps": 1000000,
"seed": 1,
"disp_file": "lcurve.out",
"disp_freq": 100,
"save_freq": 1000
}
The sections training_data and validation_data give the training dataset and validation dataset, respectively. Taking the training dataset for example, the keys are explained below:
systems provide paths of the training data systems. DeePMD-kit allows you to provide multiple systems with different numbers of atoms. This key can be a
listor astr.At each training step, DeePMD-kit randomly picks batch_size frame(s) from one of the systems. The probability of using a system is by default in proportion to the number of batches in the system. More options are available for automatically determining the probability of using systems. One can set the key auto_prob to
"prob_uniform"all systems are used with the same probability."prob_sys_size"the probability of using a system is proportional to its size (number of frames)."prob_sys_size; sidx_0:eidx_0:w_0; sidx_1:eidx_1:w_1;..."thelistof systems is divided into blocks. Blockihas systems ranging fromsidx_itoeidx_i. The probability of using a system from blockiis proportional tow_i. Within one block, the probability of using a system is proportional to its size.
An example of using
"auto_prob"is given below. The probability of usingsystems[2]is 0.4, and the sum of the probabilities of usingsystems[0]andsystems[1]is 0.6. If the number of frames insystems[1]is twice ofsystem[0], then the probability of usingsystem[1]is 0.4 and that ofsystem[0]is 0.2.
"training_data": {
"systems": ["../data_water/data_0/", "../data_water/data_1/", "../data_water/data_2/"],
"auto_prob": "prob_sys_size; 0:2:0.6; 2:3:0.4",
"batch_size": "auto"
}
The probability of using systems can also be specified explicitly with key sys_probs which is a list having the length of the number of systems. For example
"training_data": {
"systems": ["../data_water/data_0/", "../data_water/data_1/", "../data_water/data_2/"],
"sys_probs": [0.5, 0.3, 0.2],
"batch_size": "auto:32"
}
The key batch_size specifies the number of frames used to train or validate the model in a training step. It can be set to
list: the length of which is the same as the systems. The batch size of each system is given by the elements of the list.int: all systems use the same batch size."auto": the same as"auto:32", see"auto:N""auto:N": automatically determines the batch size so that the batch_size times the number of atoms in the system is no less thanN.
The key numb_batch in validate_data gives the number of batches of model validation. Note that the batches may not be from the same system
The section mixed_precision specifies the mixed precision settings, which will enable the mixed precision training workflow for DeePMD-kit. The keys are explained below:
output_prec precision used in the output tensors, only
float32is supported currently.compute_prec precision used in the computing tensors, only
float16is supported currently. Note there are several limitations about mixed precision training:Only se_e2_a type descriptor is supported by the mixed precision training workflow.
The precision of the embedding net and the fitting net are forced to be set to
float32.
Other keys in the training section are explained below:
numb_steps The number of training steps.
seed The random seed for getting frames from the training data set.
disp_file The file for printing learning curve.
disp_freq The frequency of printing learning curve. Set in the unit of training steps
save_freq The frequency of saving checkpoint.
Options and environment variables
Several command line options can be passed to dp train, which can be checked with
$ dp train --help
An explanation will be provided
positional arguments:
INPUT the input json database
optional arguments:
-h, --help show this help message and exit
--init-model INIT_MODEL
Initialize a model by the provided checkpoint
--restart RESTART Restart the training from the provided checkpoint
--init-frz-model INIT_FRZ_MODEL
Initialize the training from the frozen model.
--skip-neighbor-stat Skip calculating neighbor statistics. Sel checking, automatic sel, and model compression will be disabled. (default: False)
--init-model model.ckpt, initializes the model training with an existing model that is stored in the path prefix of checkpoint files model.ckpt, the network architectures should match.
--restart model.ckpt, continues the training from the checkpoint model.ckpt.
--init-frz-model frozen_model.pb, initializes the training with an existing model that is stored in frozen_model.pb.
--skip-neighbor-stat will skip calculating neighbor statistics if one is concerned about performance. Some features will be disabled.
To maximize the performance, one should follow FAQ: How to control the parallelism of a job to control the number of threads.
One can set other environmental variables:
Environment variables | Allowed value | Default value | Usage |
|---|---|---|---|
DP_INTERFACE_PREC |
|
| Control high (double) or low (float) precision of training. |
DP_AUTO_PARALLELIZATION | 0, 1 | 0 | Enable auto parallelization for CPU operators. |
DP_JIT | 0, 1 | 0 | Enable JIT. Note that this option may either improve or decrease the performance. Requires TensorFlow supports JIT. |
Adjust sel of a frozen model
One can use --init-frz-model features to adjust (increase or decrease) sel of a existing model. Firstly, one needs to adjust sel in input.json. For example, adjust from [46, 92] to [23, 46].
"model": {
"descriptor": {
"sel": [23, 46]
}
}
To obtain the new model at once, numb_steps should be set to zero:
"training": {
"numb_steps": 0
}
Then, one can initialize the training from the frozen model and freeze the new model at once:
dp train input.json --init-frz-model frozen_model.pb
dp freeze -o frozen_model_adjusted_sel.pb
Two models should give the same result when the input satisfies both constraints.
Note: At this time, this feature is only supported by se_e2_a descriptor with set_davg_true enabled, or hybrid composed of the above descriptors.
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Training Parameters
Note
One can load, modify, and export the input file by using our effective web-based tool DP-GUI online or hosted using the command line interface dp gui. All training parameters below can be set in DP-GUI. By clicking “SAVE JSON”, one can download the input file for furthur training.
- model:
- type:
dictargument path:model- type_map:
- type:
typing.List[str], optionalargument path:model/type_mapA list of strings. Give the name to each type of atoms. It is noted that the number of atom type of training system must be less than 128 in a GPU environment. If not given, type.raw in each system should use the same type indexes, and type_map.raw will take no effect.
- data_stat_nbatch:
- type:
int, optional, default:10argument path:model/data_stat_nbatchThe model determines the normalization from the statistics of the data. This key specifies the number of frames in each system used for statistics.
- data_stat_protect:
- type:
float, optional, default:0.01argument path:model/data_stat_protectProtect parameter for atomic energy regression.
- data_bias_nsample:
- type:
int, optional, default:10argument path:model/data_bias_nsampleThe number of training samples in a system to compute and change the energy bias.
- use_srtab:
- type:
str, optionalargument path:model/use_srtabThe table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha:
- type:
float, optionalargument path:model/smin_alphaThe short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin:
- type:
float, optionalargument path:model/sw_rminThe lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmax:
- type:
float, optionalargument path:model/sw_rmaxThe upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- srtab_add_bias:
- type:
bool, optional, default:Trueargument path:model/srtab_add_biasWhether add energy bias from the statistics of the data to short-range tabulated atomic energy. It only takes effect when use_srtab is provided.
- type_embedding:
- type:
dict, optionalargument path:model/type_embeddingThe type embedding.
- neuron:
- type:
typing.List[int], optional, default:[8]argument path:model/type_embedding/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model/type_embedding/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model/type_embedding/resnet_dtWhether to use a “Timestep” in the skip connection
- precision:
- type:
str, optional, default:defaultargument path:model/type_embedding/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model/type_embedding/trainableIf the parameters in the embedding net are trainable
- seed:
- type:
NoneType|int, optional, default:Noneargument path:model/type_embedding/seedRandom seed for parameter initialization
- modifier:
- type:
dict, optionalargument path:model/modifierThe modifier of model output.
Depending on the value of type, different sub args are accepted.
- type:
The type of modifier. See explanation below.
-dipole_charge: Use WFCC to model the electronic structure of the system. Correct the long-range interaction
When type is set to
dipole_charge:- model_name:
- type:
strargument path:model/modifier[dipole_charge]/model_nameThe name of the frozen dipole model file.
- model_charge_map:
- type:
typing.List[float]argument path:model/modifier[dipole_charge]/model_charge_mapThe charge of the WFCC. The list length should be the same as the `sel_type <model/fitting_net[dipole]/sel_type_>`_.
- sys_charge_map:
- type:
typing.List[float]argument path:model/modifier[dipole_charge]/sys_charge_mapThe charge of real atoms. The list length should be the same as the type_map
- ewald_beta:
- type:
float, optional, default:0.4argument path:model/modifier[dipole_charge]/ewald_betaThe splitting parameter of Ewald sum. Unit is A^-1
- ewald_h:
- type:
float, optional, default:1.0argument path:model/modifier[dipole_charge]/ewald_hThe grid spacing of the FFT grid. Unit is A
- compress:
- type:
dict, optionalargument path:model/compressModel compression configurations
- spin:
- type:
dict, optionalargument path:model/spinThe settings for systems with spin.
- use_spin:
- type:
typing.List[bool]argument path:model/spin/use_spinWhether to use atomic spin model for each atom type
- spin_norm:
- type:
typing.List[float]argument path:model/spin/spin_normThe magnitude of atomic spin for each atom type with spin
- virtual_len:
- type:
typing.List[float]argument path:model/spin/virtual_lenThe distance between virtual atom representing spin and its corresponding real atom for each atom type with spin
Depending on the value of type, different sub args are accepted.
- type:
- type:
str(flag key), default:standardargument path:model/type
When type is set to
standard:Stardard model, which contains a descriptor and a fitting.
- descriptor:
- type:
dictargument path:model[standard]/descriptorThe descriptor of atomic environment.
Depending on the value of type, different sub args are accepted.
- type:
- type:
str(flag key)argument path:model[standard]/descriptor/typepossible choices:loc_frame,se_e2_a,se_e3,se_a_tpe,se_e2_r,hybrid,se_atten,se_atten_v2,se_a_ebd_v2,se_a_maskThe type of the descritpor. See explanation below.
loc_frame: Defines a local frame at each atom, and the compute the descriptor as local coordinates under this frame.
se_e2_a: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor.
se_e2_r: Used by the smooth edition of Deep Potential. Only the distance between atoms is used to construct the descriptor.
se_e3: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Three-body embedding will be used by this descriptor.
se_a_tpe: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Type embedding will be used by this descriptor.
se_atten: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Attention mechanism will be used by this descriptor.
se_atten_v2: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor. Attention mechanism with new modifications will be used by this descriptor.
se_a_mask: Used by the smooth edition of Deep Potential. It can accept a variable number of atoms in a frame (Non-PBC system). aparam are required as an indicator matrix for the real/virtual sign of input atoms.
hybrid: Concatenate of a list of descriptors as a new descriptor.
When type is set to
loc_frame:- sel_a:
- type:
typing.List[int]argument path:model[standard]/descriptor[loc_frame]/sel_aA list of integers. The length of the list should be the same as the number of atom types in the system. sel_a[i] gives the selected number of type-i neighbors. The full relative coordinates of the neighbors are used by the descriptor.
- sel_r:
- type:
typing.List[int]argument path:model[standard]/descriptor[loc_frame]/sel_rA list of integers. The length of the list should be the same as the number of atom types in the system. sel_r[i] gives the selected number of type-i neighbors. Only relative distance of the neighbors are used by the descriptor. sel_a[i] + sel_r[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[loc_frame]/rcutThe cut-off radius. The default value is 6.0
- axis_rule:
- type:
typing.List[int]argument path:model[standard]/descriptor[loc_frame]/axis_ruleA list of integers. The length should be 6 times of the number of types.
axis_rule[i*6+0]: class of the atom defining the first axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance.
axis_rule[i*6+1]: type of the atom defining the first axis of type-i atom.
axis_rule[i*6+2]: index of the axis atom defining the first axis. Note that the neighbors with the same class and type are sorted according to their relative distance.
axis_rule[i*6+3]: class of the atom defining the second axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance.
axis_rule[i*6+4]: type of the atom defining the second axis of type-i atom.
axis_rule[i*6+5]: index of the axis atom defining the second axis. Note that the neighbors with the same class and type are sorted according to their relative distance.
When type is set to
se_e2_a(or its aliasse_a):- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_e2_a]/selThis parameter set the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_e2_a]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_e2_a]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_e2_a]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_e2_a]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_e2_a]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_a]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_a]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_e2_a]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_e2_a]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_e2_a]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_e2_a]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_a]/set_davg_zeroSet the normalization average to zero. This option should be set when atom_ener in the energy fitting is used
When type is set to
se_e3(or its aliasesse_at,se_a_3be,se_t):- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_e3]/selThis parameter set the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_e3]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_e3]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_e3]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_e3]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e3]/resnet_dtWhether to use a “Timestep” in the skip connection
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_e3]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_e3]/trainableIf the parameters in the embedding net are trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_e3]/seedRandom seed for parameter initialization
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e3]/set_davg_zeroSet the normalization average to zero. This option should be set when atom_ener in the energy fitting is used
When type is set to
se_a_tpe(or its aliasse_a_ebd):- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_a_tpe]/selThis parameter set the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_a_tpe]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_a_tpe]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_a_tpe]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_a_tpe]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_a_tpe]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_tpe]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_tpe]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_a_tpe]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_a_tpe]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_a_tpe]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_a_tpe]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_tpe]/set_davg_zeroSet the normalization average to zero. This option should be set when atom_ener in the energy fitting is used
- type_nchanl:
- type:
int, optional, default:4argument path:model[standard]/descriptor[se_a_tpe]/type_nchanlnumber of channels for type embedding
- type_nlayer:
- type:
int, optional, default:2argument path:model[standard]/descriptor[se_a_tpe]/type_nlayernumber of hidden layers of type embedding net
- numb_aparam:
- type:
int, optional, default:0argument path:model[standard]/descriptor[se_a_tpe]/numb_aparamdimension of atomic parameter. if set to a value > 0, the atomic parameters are embedded.
When type is set to
se_e2_r(or its aliasse_r):- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_e2_r]/selThis parameter set the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_e2_r]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_e2_r]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_e2_r]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_e2_r]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_r]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_r]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_e2_r]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_e2_r]/trainableIf the parameters in the embedding net are trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_e2_r]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_e2_r]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_e2_r]/set_davg_zeroSet the normalization average to zero. This option should be set when atom_ener in the energy fitting is used
When type is set to
hybrid:- list:
- type:
listargument path:model[standard]/descriptor[hybrid]/listA list of descriptor definitions
When type is set to
se_atten:- sel:
- type:
typing.List[int]|str|int, optional, default:autoargument path:model[standard]/descriptor[se_atten]/selThis parameter set the number of selected neighbors. Note that this parameter is a little different from that in other descriptors. Instead of separating each type of atoms, only the summation matters. And this number is highly related with the efficiency, thus one should not make it too large. Usually 200 or less is enough, far away from the GPU limitation 4096. It can be:
int. The maximum number of neighbor atoms to be considered. We recommend it to be less than 200.
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. Only the summation of sel[i] matters, and it is recommended to be less than 200. - str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_atten]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_atten]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_atten]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_atten]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_atten]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_atten]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_atten]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_atten]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_atten]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- attn:
- type:
int, optional, default:128argument path:model[standard]/descriptor[se_atten]/attnThe length of hidden vectors in attention layers
- attn_layer:
- type:
int, optional, default:2argument path:model[standard]/descriptor[se_atten]/attn_layerThe number of attention layers. Note that model compression of se_atten is only enabled when attn_layer==0 and stripped_type_embedding is True
- attn_dotr:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_atten]/attn_dotrWhether to do dot product with the normalized relative coordinates
- attn_mask:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten]/attn_maskWhether to do mask on the diagonal in the attention matrix
- stripped_type_embedding:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten]/stripped_type_embeddingWhether to strip the type embedding into a separated embedding network. Setting it to False will fall back to the previous version of se_atten which is non-compressible.
- smooth_type_embdding:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten]/smooth_type_embddingWhen using stripped type embedding, whether to dot smooth factor on the network output of type embedding to keep the network smooth, instead of setting set_davg_zero to be True.
- set_davg_zero:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_atten]/set_davg_zeroSet the normalization average to zero. This option should be set when se_atten descriptor or atom_ener in the energy fitting is used
When type is set to
se_atten_v2:- sel:
- type:
typing.List[int]|str|int, optional, default:autoargument path:model[standard]/descriptor[se_atten_v2]/selThis parameter set the number of selected neighbors. Note that this parameter is a little different from that in other descriptors. Instead of separating each type of atoms, only the summation matters. And this number is highly related with the efficiency, thus one should not make it too large. Usually 200 or less is enough, far away from the GPU limitation 4096. It can be:
int. The maximum number of neighbor atoms to be considered. We recommend it to be less than 200.
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. Only the summation of sel[i] matters, and it is recommended to be less than 200. - str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_atten_v2]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_atten_v2]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_atten_v2]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_atten_v2]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_atten_v2]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten_v2]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten_v2]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_atten_v2]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_atten_v2]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_atten_v2]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_atten_v2]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- attn:
- type:
int, optional, default:128argument path:model[standard]/descriptor[se_atten_v2]/attnThe length of hidden vectors in attention layers
- attn_layer:
- type:
int, optional, default:2argument path:model[standard]/descriptor[se_atten_v2]/attn_layerThe number of attention layers. Note that model compression of se_atten is only enabled when attn_layer==0 and stripped_type_embedding is True
- attn_dotr:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_atten_v2]/attn_dotrWhether to do dot product with the normalized relative coordinates
- attn_mask:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten_v2]/attn_maskWhether to do mask on the diagonal in the attention matrix
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_atten_v2]/set_davg_zeroSet the normalization average to zero. This option should be set when se_atten descriptor or atom_ener in the energy fitting is used
When type is set to
se_a_ebd_v2(or its aliasse_a_tpe_v2):- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_a_ebd_v2]/selThis parameter set the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- rcut:
- type:
float, optional, default:6.0argument path:model[standard]/descriptor[se_a_ebd_v2]/rcutThe cut-off radius.
- rcut_smth:
- type:
float, optional, default:0.5argument path:model[standard]/descriptor[se_a_ebd_v2]/rcut_smthWhere to start smoothing. For example the 1/r term is smoothed from rcut to rcut_smth
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_a_ebd_v2]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_a_ebd_v2]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_a_ebd_v2]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_ebd_v2]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_ebd_v2]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_a_ebd_v2]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_a_ebd_v2]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_a_ebd_v2]/seedRandom seed for parameter initialization
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_a_ebd_v2]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_ebd_v2]/set_davg_zeroSet the normalization average to zero. This option should be set when atom_ener in the energy fitting is used
When type is set to
se_a_mask:- sel:
- type:
typing.List[int]|str, optional, default:autoargument path:model[standard]/descriptor[se_a_mask]/selThis parameter sets the number of selected neighbors for each type of atom. It can be:
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. sel[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius. It is noted that the total sel value must be less than 4096 in a GPU environment.
str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
- neuron:
- type:
typing.List[int], optional, default:[10, 20, 40]argument path:model[standard]/descriptor[se_a_mask]/neuronNumber of neurons in each hidden layers of the embedding net. When two layers are of the same size or one layer is twice as large as the previous layer, a skip connection is built.
- axis_neuron:
- type:
int, optional, default:4, alias: n_axis_neuronargument path:model[standard]/descriptor[se_a_mask]/axis_neuronSize of the submatrix of G (embedding matrix).
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/descriptor[se_a_mask]/activation_functionThe activation function in the embedding net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_mask]/resnet_dtWhether to use a “Timestep” in the skip connection
- type_one_side:
- type:
bool, optional, default:Falseargument path:model[standard]/descriptor[se_a_mask]/type_one_sideIf true, the embedding network parameters vary by types of neighbor atoms only, so there will be $N_text{types}$ sets of embedding network parameters. Otherwise, the embedding network parameters vary by types of centric atoms and types of neighbor atoms, so there will be $N_text{types}^2$ sets of embedding network parameters.
- exclude_types:
- type:
typing.List[typing.List[int]], optional, default:[]argument path:model[standard]/descriptor[se_a_mask]/exclude_typesThe excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/descriptor[se_a_mask]/precisionThe precision of the embedding net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- trainable:
- type:
bool, optional, default:Trueargument path:model[standard]/descriptor[se_a_mask]/trainableIf the parameters in the embedding net is trainable
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/descriptor[se_a_mask]/seedRandom seed for parameter initialization
- fitting_net:
- type:
dictargument path:model[standard]/fitting_netThe fitting of physical properties.
Depending on the value of type, different sub args are accepted.
- type:
- type:
str(flag key), default:enerargument path:model[standard]/fitting_net/typeThe type of the fitting. See explanation below.
ener: Fit an energy model (potential energy surface).
dos : Fit a density of states model. The total density of states / site-projected density of states labels should be provided by dos.npy or atom_dos.npy in each data system. The file has number of frames lines and number of energy grid columns (times number of atoms in atom_dos.npy). See loss parameter.
dipole: Fit an atomic dipole model. Global dipole labels or atomic dipole labels for all the selected atoms (see sel_type) should be provided by dipole.npy in each data system. The file either has number of frames lines and 3 times of number of selected atoms columns, or has number of frames lines and 3 columns. See loss parameter.
polar: Fit an atomic polarizability model. Global polarizazbility labels or atomic polarizability labels for all the selected atoms (see sel_type) should be provided by polarizability.npy in each data system. The file eith has number of frames lines and 9 times of number of selected atoms columns, or has number of frames lines and 9 columns. See loss parameter.
When type is set to
ener:- numb_fparam:
- type:
int, optional, default:0argument path:model[standard]/fitting_net[ener]/numb_fparamThe dimension of the frame parameter. If set to >0, file fparam.npy should be included to provided the input fparams.
- numb_aparam:
- type:
int, optional, default:0argument path:model[standard]/fitting_net[ener]/numb_aparamThe dimension of the atomic parameter. If set to >0, file aparam.npy should be included to provided the input aparams.
- neuron:
- type:
typing.List[int], optional, default:[120, 120, 120], alias: n_neuronargument path:model[standard]/fitting_net[ener]/neuronThe number of neurons in each hidden layers of the fitting net. When two hidden layers are of the same size, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/fitting_net[ener]/activation_functionThe activation function in the fitting net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/fitting_net[ener]/precisionThe precision of the fitting net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- resnet_dt:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[ener]/resnet_dtWhether to use a “Timestep” in the skip connection
- trainable:
- type:
typing.List[bool]|bool, optional, default:Trueargument path:model[standard]/fitting_net[ener]/trainableWhether the parameters in the fitting net are trainable. This option can be
bool: True if all parameters of the fitting net are trainable, False otherwise.
list of bool: Specifies if each layer is trainable. Since the fitting net is composed by hidden layers followed by a output layer, the length of this list should be equal to len(neuron)+1.
- rcond:
- type:
float|NoneType, optional, default:Noneargument path:model[standard]/fitting_net[ener]/rcondThe condition number used to determine the inital energy shift for each type of atoms. See rcond in
numpy.linalg.lstsq()for more details.
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/fitting_net[ener]/seedRandom seed for parameter initialization of the fitting net
- atom_ener:
- type:
typing.List[typing.Optional[float]], optional, default:[]argument path:model[standard]/fitting_net[ener]/atom_enerSpecify the atomic energy in vacuum for each type
- layer_name:
- type:
typing.List[str], optionalargument path:model[standard]/fitting_net[ener]/layer_nameThe name of the each layer. The length of this list should be equal to n_neuron + 1. If two layers, either in the same fitting or different fittings, have the same name, they will share the same neural network parameters. The shape of these layers should be the same. If null is given for a layer, parameters will not be shared.
- use_aparam_as_mask:
- type:
bool, optional, default:Falseargument path:model[standard]/fitting_net[ener]/use_aparam_as_maskWhether to use the aparam as a mask in input.If True, the aparam will not be used in fitting net for embedding.When descrpt is se_a_mask, the aparam will be used as a mask to indicate the input atom is real/virtual. And use_aparam_as_mask should be set to True.
When type is set to
dos:- numb_fparam:
- type:
int, optional, default:0argument path:model[standard]/fitting_net[dos]/numb_fparamThe dimension of the frame parameter. If set to >0, file fparam.npy should be included to provided the input fparams.
- numb_aparam:
- type:
int, optional, default:0argument path:model[standard]/fitting_net[dos]/numb_aparamThe dimension of the atomic parameter. If set to >0, file aparam.npy should be included to provided the input aparams.
- neuron:
- type:
typing.List[int], optional, default:[120, 120, 120]argument path:model[standard]/fitting_net[dos]/neuronThe number of neurons in each hidden layers of the fitting net. When two hidden layers are of the same size, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/fitting_net[dos]/activation_functionThe activation function in the fitting net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- precision:
- type:
str, optional, default:float64argument path:model[standard]/fitting_net[dos]/precisionThe precision of the fitting net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- resnet_dt:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[dos]/resnet_dtWhether to use a “Timestep” in the skip connection
- trainable:
- type:
typing.List[bool]|bool, optional, default:Trueargument path:model[standard]/fitting_net[dos]/trainableWhether the parameters in the fitting net are trainable. This option can be
bool: True if all parameters of the fitting net are trainable, False otherwise.
list of bool: Specifies if each layer is trainable. Since the fitting net is composed by hidden layers followed by a output layer, the length of tihs list should be equal to len(neuron)+1.
- rcond:
- type:
float|NoneType, optional, default:Noneargument path:model[standard]/fitting_net[dos]/rcondThe condition number used to determine the inital energy shift for each type of atoms. See rcond in
numpy.linalg.lstsq()for more details.
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/fitting_net[dos]/seedRandom seed for parameter initialization of the fitting net
- numb_dos:
- type:
int, optional, default:300argument path:model[standard]/fitting_net[dos]/numb_dosThe number of gridpoints on which the DOS is evaluated (NEDOS in VASP)
When type is set to
polar:- neuron:
- type:
typing.List[int], optional, default:[120, 120, 120], alias: n_neuronargument path:model[standard]/fitting_net[polar]/neuronThe number of neurons in each hidden layers of the fitting net. When two hidden layers are of the same size, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/fitting_net[polar]/activation_functionThe activation function in the fitting net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[polar]/resnet_dtWhether to use a “Timestep” in the skip connection
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/fitting_net[polar]/precisionThe precision of the fitting net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- fit_diag:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[polar]/fit_diagFit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix.
- scale:
- type:
float|typing.List[float], optional, default:1.0argument path:model[standard]/fitting_net[polar]/scaleThe output of the fitting net (polarizability matrix) will be scaled by
scale
- shift_diag:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[polar]/shift_diagWhether to shift the diagonal of polar, which is beneficial to training. Default is true.
- sel_type:
- type:
typing.List[int]|NoneType|int, optional, alias: pol_typeargument path:model[standard]/fitting_net[polar]/sel_typeThe atom types for which the atomic polarizability will be provided. If not set, all types will be selected.
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/fitting_net[polar]/seedRandom seed for parameter initialization of the fitting net
When type is set to
dipole:- neuron:
- type:
typing.List[int], optional, default:[120, 120, 120], alias: n_neuronargument path:model[standard]/fitting_net[dipole]/neuronThe number of neurons in each hidden layers of the fitting net. When two hidden layers are of the same size, a skip connection is built.
- activation_function:
- type:
str, optional, default:tanhargument path:model[standard]/fitting_net[dipole]/activation_functionThe activation function in the fitting net. Supported activation functions are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”. Note that “gelu” denotes the custom operator version, and “gelu_tf” denotes the TF standard version. If you set “None” or “none” here, no activation function will be used.
- resnet_dt:
- type:
bool, optional, default:Trueargument path:model[standard]/fitting_net[dipole]/resnet_dtWhether to use a “Timestep” in the skip connection
- precision:
- type:
str, optional, default:defaultargument path:model[standard]/fitting_net[dipole]/precisionThe precision of the fitting net parameters, supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”. Default follows the interface precision.
- sel_type:
- type:
typing.List[int]|NoneType|int, optional, alias: dipole_typeargument path:model[standard]/fitting_net[dipole]/sel_typeThe atom types for which the atomic dipole will be provided. If not set, all types will be selected.
- seed:
- type:
NoneType|int, optionalargument path:model[standard]/fitting_net[dipole]/seedRandom seed for parameter initialization of the fitting net
When type is set to
multi:Multiple-task model.
- descriptor:
- type:
dictargument path:model[multi]/descriptorThe descriptor of atomic environment. See model[standard]/descriptor for details.
- fitting_net_dict:
- type:
dictargument path:model[multi]/fitting_net_dictThe dictionary of multiple fitting nets in multi-task mode. Each fitting_net_dict[fitting_key] is the single definition of fitting of physical properties with user-defined name fitting_key.
When type is set to
frozen:- model_file:
- type:
strargument path:model[frozen]/model_filePath to the frozen model file.
When type is set to
pairtab:Pairwise tabulation energy model.
- tab_file:
- type:
strargument path:model[pairtab]/tab_filePath to the tabulation file.
- rcut:
- type:
floatargument path:model[pairtab]/rcutThe cut-off radius.
- sel:
- type:
typing.List[int]|str|intargument path:model[pairtab]/selThis parameter set the number of selected neighbors. Note that this parameter is a little different from that in other descriptors. Instead of separating each type of atoms, only the summation matters. And this number is highly related with the efficiency, thus one should not make it too large. Usually 200 or less is enough, far away from the GPU limitation 4096. It can be:
int. The maximum number of neighbor atoms to be considered. We recommend it to be less than 200.
List[int]. The length of the list should be the same as the number of atom types in the system. sel[i] gives the selected number of type-i neighbors. Only the summation of sel[i] matters, and it is recommended to be less than 200. - str. Can be “auto:factor” or “auto”. “factor” is a float number larger than 1. This option will automatically determine the sel. In detail it counts the maximal number of neighbors with in the cutoff radius for each type of neighbor, then multiply the maximum by the “factor”. Finally the number is wraped up to 4 divisible. The option “auto” is equivalent to “auto:1.1”.
When type is set to
pairwise_dprc:- qm_model:
- type:
dictargument path:model[pairwise_dprc]/qm_model
- qmmm_model:
- type:
dictargument path:model[pairwise_dprc]/qmmm_model
When type is set to
linear_ener:- models:
- type:
list|dictargument path:model[linear_ener]/modelsThe sub-models.
- weights:
- type:
list|strargument path:model[linear_ener]/weightsIf the type is list of float, a list of weights for each model. If “mean”, the weights are set to be 1 / len(models). If “sum”, the weights are set to be 1.
- learning_rate:
- type:
dict, optionalargument path:learning_rateThe definitio of learning rate
- scale_by_worker:
- type:
str, optional, default:linearargument path:learning_rate/scale_by_workerWhen parallel training or batch size scaled, how to alter learning rate. Valid values are linear`(default), `sqrt or none.
Depending on the value of type, different sub args are accepted.
- type:
The type of the learning rate.
When type is set to
exp:- start_lr:
- type:
float, optional, default:0.001argument path:learning_rate[exp]/start_lrThe learning rate at the start of the training.
- stop_lr:
- type:
float, optional, default:1e-08argument path:learning_rate[exp]/stop_lrThe desired learning rate at the end of the training.
- decay_steps:
- type:
int, optional, default:5000argument path:learning_rate[exp]/decay_stepsThe learning rate is decaying every this number of training steps.
- learning_rate_dict:
- type:
dict, optionalargument path:learning_rate_dictThe dictionary of definitions of learning rates in multi-task mode. Each learning_rate_dict[fitting_key], with user-defined name fitting_key in model/fitting_net_dict, is the single definition of learning rate.
- loss:
- type:
dict, optionalargument path:lossThe definition of loss function. The loss type should be set to tensor, ener or left unset.
Depending on the value of type, different sub args are accepted.
- type:
When type is set to
ener:- start_pref_e:
- type:
float|int, optional, default:0.02argument path:loss[ener]/start_pref_eThe prefactor of energy loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the energy label should be provided by file energy.npy in each data system. If both start_pref_e and limit_pref_e are set to 0, then the energy will be ignored.
- limit_pref_e:
- type:
float|int, optional, default:1.0argument path:loss[ener]/limit_pref_eThe prefactor of energy loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_f:
- type:
float|int, optional, default:1000argument path:loss[ener]/start_pref_fThe prefactor of force loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the force label should be provided by file force.npy in each data system. If both start_pref_f and limit_pref_f are set to 0, then the force will be ignored.
- limit_pref_f:
- type:
float|int, optional, default:1.0argument path:loss[ener]/limit_pref_fThe prefactor of force loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_v:
- type:
float|int, optional, default:0.0argument path:loss[ener]/start_pref_vThe prefactor of virial loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the virial label should be provided by file virial.npy in each data system. If both start_pref_v and limit_pref_v are set to 0, then the virial will be ignored.
- limit_pref_v:
- type:
float|int, optional, default:0.0argument path:loss[ener]/limit_pref_vThe prefactor of virial loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_ae:
- type:
float|int, optional, default:0.0argument path:loss[ener]/start_pref_aeThe prefactor of atomic energy loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the atom_ener label should be provided by file atom_ener.npy in each data system. If both start_pref_ae and limit_pref_ae are set to 0, then the atomic energy will be ignored.
- limit_pref_ae:
- type:
float|int, optional, default:0.0argument path:loss[ener]/limit_pref_aeThe prefactor of atomic energy loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_pf:
- type:
float|int, optional, default:0.0argument path:loss[ener]/start_pref_pfThe prefactor of atomic prefactor force loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the atom_pref label should be provided by file atom_pref.npy in each data system. If both start_pref_pf and limit_pref_pf are set to 0, then the atomic prefactor force will be ignored.
- limit_pref_pf:
- type:
float|int, optional, default:0.0argument path:loss[ener]/limit_pref_pfThe prefactor of atomic prefactor force loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- relative_f:
- type:
float|NoneType, optionalargument path:loss[ener]/relative_fIf provided, relative force error will be used in the loss. The difference of force will be normalized by the magnitude of the force in the label with a shift given by relative_f, i.e. DF_i / ( || F || + relative_f ) with DF denoting the difference between prediction and label and || F || denoting the L2 norm of the label.
- enable_atom_ener_coeff:
- type:
bool, optional, default:Falseargument path:loss[ener]/enable_atom_ener_coeffIf true, the energy will be computed as sum_i c_i E_i. c_i should be provided by file atom_ener_coeff.npy in each data system, otherwise it’s 1.
- start_pref_gf:
- type:
float, optional, default:0.0argument path:loss[ener]/start_pref_gfThe prefactor of generalized force loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the drdq label should be provided by file drdq.npy in each data system. If both start_pref_gf and limit_pref_gf are set to 0, then the generalized force will be ignored.
- limit_pref_gf:
- type:
float, optional, default:0.0argument path:loss[ener]/limit_pref_gfThe prefactor of generalized force loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- numb_generalized_coord:
- type:
int, optional, default:0argument path:loss[ener]/numb_generalized_coordThe dimension of generalized coordinates. Required when generalized force loss is used.
When type is set to
ener_spin:- start_pref_e:
- type:
float|int, optional, default:0.02argument path:loss[ener_spin]/start_pref_eThe prefactor of energy loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the energy label should be provided by file energy.npy in each data system. If both start_pref_energy and limit_pref_energy are set to 0, then the energy will be ignored.
- limit_pref_e:
- type:
float|int, optional, default:1.0argument path:loss[ener_spin]/limit_pref_eThe prefactor of energy loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_fr:
- type:
float|int, optional, default:1000argument path:loss[ener_spin]/start_pref_frThe prefactor of force_real_atom loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the force_real_atom label should be provided by file force_real_atom.npy in each data system. If both start_pref_force_real_atom and limit_pref_force_real_atom are set to 0, then the force_real_atom will be ignored.
- limit_pref_fr:
- type:
float|int, optional, default:1.0argument path:loss[ener_spin]/limit_pref_frThe prefactor of force_real_atom loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_fm:
- type:
float|int, optional, default:10000argument path:loss[ener_spin]/start_pref_fmThe prefactor of force_magnetic loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the force_magnetic label should be provided by file force_magnetic.npy in each data system. If both start_pref_force_magnetic and limit_pref_force_magnetic are set to 0, then the force_magnetic will be ignored.
- limit_pref_fm:
- type:
float|int, optional, default:10.0argument path:loss[ener_spin]/limit_pref_fmThe prefactor of force_magnetic loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_v:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/start_pref_vThe prefactor of virial loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the virial label should be provided by file virial.npy in each data system. If both start_pref_virial and limit_pref_virial are set to 0, then the virial will be ignored.
- limit_pref_v:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/limit_pref_vThe prefactor of virial loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_ae:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/start_pref_aeThe prefactor of atom_ener loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the atom_ener label should be provided by file atom_ener.npy in each data system. If both start_pref_atom_ener and limit_pref_atom_ener are set to 0, then the atom_ener will be ignored.
- limit_pref_ae:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/limit_pref_aeThe prefactor of atom_ener loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_pf:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/start_pref_pfThe prefactor of atom_pref loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the atom_pref label should be provided by file atom_pref.npy in each data system. If both start_pref_atom_pref and limit_pref_atom_pref are set to 0, then the atom_pref will be ignored.
- limit_pref_pf:
- type:
float|int, optional, default:0.0argument path:loss[ener_spin]/limit_pref_pfThe prefactor of atom_pref loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- relative_f:
- type:
float|NoneType, optionalargument path:loss[ener_spin]/relative_fIf provided, relative force error will be used in the loss. The difference of force will be normalized by the magnitude of the force in the label with a shift given by relative_f, i.e. DF_i / ( || F || + relative_f ) with DF denoting the difference between prediction and label and || F || denoting the L2 norm of the label.
- enable_atom_ener_coeff:
- type:
bool, optional, default:Falseargument path:loss[ener_spin]/enable_atom_ener_coeffIf true, the energy will be computed as sum_i c_i E_i. c_i should be provided by file atom_ener_coeff.npy in each data system, otherwise it’s 1.
When type is set to
dos:- start_pref_dos:
- type:
float|int, optional, default:0.0argument path:loss[dos]/start_pref_dosThe prefactor of Density of State (DOS) loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the Density of State (DOS) label should be provided by file Density of State (DOS).npy in each data system. If both start_pref_Density of State (DOS) and limit_pref_Density of State (DOS) are set to 0, then the Density of State (DOS) will be ignored.
- limit_pref_dos:
- type:
float|int, optional, default:0.0argument path:loss[dos]/limit_pref_dosThe prefactor of Density of State (DOS) loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_cdf:
- type:
float|int, optional, default:0.0argument path:loss[dos]/start_pref_cdfThe prefactor of Cumulative Distribution Function (cumulative intergral of DOS) loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the Cumulative Distribution Function (cumulative intergral of DOS) label should be provided by file Cumulative Distribution Function (cumulative intergral of DOS).npy in each data system. If both start_pref_Cumulative Distribution Function (cumulative intergral of DOS) and limit_pref_Cumulative Distribution Function (cumulative intergral of DOS) are set to 0, then the Cumulative Distribution Function (cumulative intergral of DOS) will be ignored.
- limit_pref_cdf:
- type:
float|int, optional, default:0.0argument path:loss[dos]/limit_pref_cdfThe prefactor of Cumulative Distribution Function (cumulative intergral of DOS) loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_ados:
- type:
float|int, optional, default:1.0argument path:loss[dos]/start_pref_adosThe prefactor of atomic DOS (site-projected DOS) loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the atomic DOS (site-projected DOS) label should be provided by file atomic DOS (site-projected DOS).npy in each data system. If both start_pref_atomic DOS (site-projected DOS) and limit_pref_atomic DOS (site-projected DOS) are set to 0, then the atomic DOS (site-projected DOS) will be ignored.
- limit_pref_ados:
- type:
float|int, optional, default:1.0argument path:loss[dos]/limit_pref_adosThe prefactor of atomic DOS (site-projected DOS) loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
- start_pref_acdf:
- type:
float|int, optional, default:0.0argument path:loss[dos]/start_pref_acdfThe prefactor of Cumulative integral of atomic DOS loss at the start of the training. Should be larger than or equal to 0. If set to none-zero value, the Cumulative integral of atomic DOS label should be provided by file Cumulative integral of atomic DOS.npy in each data system. If both start_pref_Cumulative integral of atomic DOS and limit_pref_Cumulative integral of atomic DOS are set to 0, then the Cumulative integral of atomic DOS will be ignored.
- limit_pref_acdf:
- type:
float|int, optional, default:0.0argument path:loss[dos]/limit_pref_acdfThe prefactor of Cumulative integral of atomic DOS loss at the limit of the training, Should be larger than or equal to 0. i.e. the training step goes to infinity.
When type is set to
tensor:- pref:
- type:
float|intargument path:loss[tensor]/prefThe prefactor of the weight of global loss. It should be larger than or equal to 0. If controls the weight of loss corresponding to global label, i.e. ‘polarizability.npy` or dipole.npy, whose shape should be #frames x [9 or 3]. If it’s larger than 0.0, this npy should be included.
- pref_atomic:
- type:
float|intargument path:loss[tensor]/pref_atomicThe prefactor of the weight of atomic loss. It should be larger than or equal to 0. If controls the weight of loss corresponding to atomic label, i.e. atomic_polarizability.npy or atomic_dipole.npy, whose shape should be #frames x ([9 or 3] x #selected atoms). If it’s larger than 0.0, this npy should be included. Both pref and pref_atomic should be provided, and either can be set to 0.0.
- loss_dict:
- type:
dict, optionalargument path:loss_dictThe dictionary of definitions of multiple loss functions in multi-task mode. Each loss_dict[fitting_key], with user-defined name fitting_key in model/fitting_net_dict, is the single definition of loss function, whose type should be set to tensor, ener or left unset.
- training:
- type:
dictargument path:trainingThe training options.
- training_data:
- type:
dict, optionalargument path:training/training_dataConfigurations of training data.
- systems:
- type:
str|typing.List[str]argument path:training/training_data/systemsThe data systems for training. This key can be provided with a list that specifies the systems, or be provided with a string by which the prefix of all systems are given and the list of the systems is automatically generated.
- set_prefix:
- type:
str, optional, default:setargument path:training/training_data/set_prefixThe prefix of the sets in the systems.
- batch_size:
- type:
typing.List[int]|str|int, optional, default:autoargument path:training/training_data/batch_sizeThis key can be
list: the length of which is the same as the systems. The batch size of each system is given by the elements of the list.
int: all systems use the same batch size.
string “auto”: automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than 32.
string “auto:N”: automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than N.
string “mixed:N”: the batch data will be sampled from all systems and merged into a mixed system with the batch size N. Only support the se_atten descriptor.
If MPI is used, the value should be considered as the batch size per task.
- auto_prob:
- type:
str, optional, default:prob_sys_size, alias: auto_prob_styleargument path:training/training_data/auto_probDetermine the probability of systems automatically. The method is assigned by this key and can be
“prob_uniform” : the probability all the systems are equal, namely 1.0/self.get_nsystems()
“prob_sys_size” : the probability of a system is proportional to the number of batches in the system
“prob_sys_size;stt_idx:end_idx:weight;stt_idx:end_idx:weight;…” : the list of systems is devided into blocks. A block is specified by stt_idx:end_idx:weight, where stt_idx is the starting index of the system, end_idx is then ending (not including) index of the system, the probabilities of the systems in this block sums up to weight, and the relatively probabilities within this block is proportional to the number of batches in the system.
- sys_probs:
- type:
typing.List[float]|NoneType, optional, default:None, alias: sys_weightsargument path:training/training_data/sys_probsA list of float if specified. Should be of the same length as systems, specifying the probability of each system.
- validation_data:
- type:
dict|NoneType, optional, default:Noneargument path:training/validation_dataConfigurations of validation data. Similar to that of training data, except that a numb_btch argument may be configured
- systems:
- type:
str|typing.List[str]argument path:training/validation_data/systemsThe data systems for validation. This key can be provided with a list that specifies the systems, or be provided with a string by which the prefix of all systems are given and the list of the systems is automatically generated.
- set_prefix:
- type:
str, optional, default:setargument path:training/validation_data/set_prefixThe prefix of the sets in the systems.
- batch_size:
- type:
typing.List[int]|str|int, optional, default:autoargument path:training/validation_data/batch_sizeThis key can be
list: the length of which is the same as the systems. The batch size of each system is given by the elements of the list.
int: all systems use the same batch size.
string “auto”: automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than 32.
string “auto:N”: automatically determines the batch size so that the batch_size times the number of atoms in the system is no less than N.
- auto_prob:
- type:
str, optional, default:prob_sys_size, alias: auto_prob_styleargument path:training/validation_data/auto_probDetermine the probability of systems automatically. The method is assigned by this key and can be
“prob_uniform” : the probability all the systems are equal, namely 1.0/self.get_nsystems()
“prob_sys_size” : the probability of a system is proportional to the number of batches in the system
“prob_sys_size;stt_idx:end_idx:weight;stt_idx:end_idx:weight;…” : the list of systems is devided into blocks. A block is specified by stt_idx:end_idx:weight, where stt_idx is the starting index of the system, end_idx is then ending (not including) index of the system, the probabilities of the systems in this block sums up to weight, and the relatively probabilities within this block is proportional to the number of batches in the system.
- sys_probs:
- type:
typing.List[float]|NoneType, optional, default:None, alias: sys_weightsargument path:training/validation_data/sys_probsA list of float if specified. Should be of the same length as systems, specifying the probability of each system.
- numb_btch:
- type:
int, optional, default:1, alias: numb_batchargument path:training/validation_data/numb_btchAn integer that specifies the number of batches to be sampled for each validation period.
- mixed_precision:
- type:
dict, optionalargument path:training/mixed_precisionConfigurations of mixed precision.
- output_prec:
- type:
str, optional, default:float32argument path:training/mixed_precision/output_precThe precision for mixed precision params. ” “The trainable variables precision during the mixed precision training process, ” “supported options are float32 only currently.
- compute_prec:
- type:
strargument path:training/mixed_precision/compute_precThe precision for mixed precision compute. ” “The compute precision during the mixed precision training process, “” “supported options are float16 and bfloat16 currently.
- numb_steps:
- type:
int, alias: stop_batchargument path:training/numb_stepsNumber of training batch. Each training uses one batch of data.
- seed:
- type:
NoneType|int, optionalargument path:training/seedThe random seed for getting frames from the training data set.
- disp_file:
- type:
str, optional, default:lcurve.outargument path:training/disp_fileThe file for printing learning curve.
- disp_freq:
- type:
int, optional, default:1000argument path:training/disp_freqThe frequency of printing learning curve.
- save_freq:
- type:
int, optional, default:1000argument path:training/save_freqThe frequency of saving check point.
- save_ckpt:
- type:
str, optional, default:model.ckptargument path:training/save_ckptThe path prefix of saving check point files.
- max_ckpt_keep:
- type:
int, optional, default:5argument path:training/max_ckpt_keepThe maximum number of checkpoints to keep. The oldest checkpoints will be deleted once the number of checkpoints exceeds max_ckpt_keep. Defaults to 5.
- disp_training:
- type:
bool, optional, default:Trueargument path:training/disp_trainingDisplaying verbose information during training.
- time_training:
- type:
bool, optional, default:Trueargument path:training/time_trainingTiming durining training.
- profiling:
- type:
bool, optional, default:Falseargument path:training/profilingProfiling during training.
- profiling_file:
- type:
str, optional, default:timeline.jsonargument path:training/profiling_fileOutput file for profiling.
- enable_profiler:
- type:
bool, optional, default:Falseargument path:training/enable_profilerEnable TensorFlow Profiler (available in TensorFlow 2.3) to analyze performance. The log will be saved to tensorboard_log_dir.
- tensorboard:
- type:
bool, optional, default:Falseargument path:training/tensorboardEnable tensorboard
- tensorboard_log_dir:
- type:
str, optional, default:logargument path:training/tensorboard_log_dirThe log directory of tensorboard outputs
- tensorboard_freq:
- type:
int, optional, default:1argument path:training/tensorboard_freqThe frequency of writing tensorboard events.
- data_dict:
- type:
dict, optionalargument path:training/data_dictThe dictionary of multi DataSystems in multi-task mode. Each data_dict[fitting_key], with user-defined name fitting_key in model/fitting_net_dict, contains training data and optional validation data definitions.
- fitting_weight:
- type:
dict, optionalargument path:training/fitting_weightEach fitting_weight[fitting_key], with user-defined name fitting_key in model/fitting_net_dict, is the training weight of fitting net fitting_key. Fitting nets with higher weights will be selected with higher probabilities to be trained in one step. Weights will be normalized and minus ones will be ignored. If not set, each fitting net will be equally selected when training.
- nvnmd:
- type:
dict, optionalargument path:nvnmdThe nvnmd options.
- version:
- type:
intargument path:nvnmd/versionconfiguration the nvnmd version (0 | 1), 0 for 4 types, 1 for 32 types
- max_nnei:
- type:
intargument path:nvnmd/max_nneiconfiguration the max number of neighbors, 128|256 for version 0, 128 for version 1
- net_size:
- type:
intargument path:nvnmd/net_sizeconfiguration the number of nodes of fitting_net, just can be set as 128
- map_file:
- type:
strargument path:nvnmd/map_fileA file containing the mapping tables to replace the calculation of embedding nets
- config_file:
- type:
strargument path:nvnmd/config_fileA file containing the parameters about how to implement the model in certain hardware
- weight_file:
- type:
strargument path:nvnmd/weight_filea *.npy file containing the weights of the model
- enable:
- type:
boolargument path:nvnmd/enableenable the nvnmd training
- restore_descriptor:
- type:
boolargument path:nvnmd/restore_descriptorenable to restore the parameter of embedding_net from weight.npy
- restore_fitting_net:
- type:
boolargument path:nvnmd/restore_fitting_netenable to restore the parameter of fitting_net from weight.npy
- quantize_descriptor:
- type:
boolargument path:nvnmd/quantize_descriptorenable the quantizatioin of descriptor
- quantize_fitting_net:
- type:
boolargument path:nvnmd/quantize_fitting_netenable the quantizatioin of fitting_net
Parallel training
Currently, parallel training is enabled in a synchronized way with help of Horovod. Depending on the number of training processes (according to MPI context) and the number of GPU cards available, DeePMD-kit will decide whether to launch the training in parallel (distributed) mode or in serial mode. Therefore, no additional options are specified in your JSON/YAML input file.
Tuning learning rate
Horovod works in the data-parallel mode, resulting in a larger global batch size. For example, the real batch size is 8 when batch_size is set to 2 in the input file and you launch 4 workers. Thus, learning_rate is automatically scaled by the number of workers for better convergence. Technical details of such heuristic rule are discussed at Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour.
The number of decay steps required to achieve the same accuracy can decrease by the number of cards (e.g., 1/2 of steps in the above case), but needs to be scaled manually in the input file.
In some cases, it won’t work well when scaling the learning rate by worker count in a linear way. Then you can try sqrt or none by setting argument scale_by_worker like below.
"learning_rate" :{
"scale_by_worker": "none",
"type": "exp"
}
Scaling test
Testing examples/water/se_e2_a on an 8-GPU host, linear acceleration can be observed with the increasing number of cards.
Num of GPU cards | Seconds every 100 samples | Samples per second | Speed up |
|---|---|---|---|
1 | 1.4515 | 68.89 | 1.00 |
2 | 1.5962 | 62.65*2 | 1.82 |
4 | 1.7635 | 56.71*4 | 3.29 |
8 | 1.7267 | 57.91*8 | 6.72 |
How to use
Training workers can be launched with horovodrun. The following command launches 4 processes on the same host:
CUDA_VISIBLE_DEVICES=4,5,6,7 horovodrun -np 4 \
dp train --mpi-log=workers input.json
Need to mention, the environment variable CUDA_VISIBLE_DEVICES must be set to control parallelism on the occupied host where one process is bound to one GPU card.
To maximize the performance, one should follow FAQ: How to control the parallelism of a job to control the number of threads.
When using MPI with Horovod, horovodrun is a simple wrapper around mpirun. In the case where fine-grained control over options is passed to mpirun, mpirun can be invoked directly, and it will be detected automatically by Horovod, e.g.,
CUDA_VISIBLE_DEVICES=4,5,6,7 mpirun -l -launcher=fork -hosts=localhost -np 4 \
dp train --mpi-log=workers input.json
this is sometimes necessary for an HPC environment.
Whether distributed workers are initiated can be observed in the “Summary of the training” section in the log (world size > 1, and distributed).
[0] DEEPMD INFO ---Summary of the training---------------------------------------
[0] DEEPMD INFO distributed
[0] DEEPMD INFO world size: 4
[0] DEEPMD INFO my rank: 0
[0] DEEPMD INFO node list: ['exp-13-57']
[0] DEEPMD INFO running on: exp-13-57
[0] DEEPMD INFO computing device: gpu:0
[0] DEEPMD INFO CUDA_VISIBLE_DEVICES: 0,1,2,3
[0] DEEPMD INFO Count of visible GPU: 4
[0] DEEPMD INFO num_intra_threads: 0
[0] DEEPMD INFO num_inter_threads: 0
[0] DEEPMD INFO -----------------------------------------------------------------
Logging
What’s more, 2 command-line arguments are defined to control the logging behavior when performing parallel training with MPI.
optional arguments:
-l LOG_PATH, --log-path LOG_PATH
set log file to log messages to disk, if not
specified, the logs will only be output to console
(default: None)
-m {master,collect,workers}, --mpi-log {master,collect,workers}
Set the manner of logging when running with MPI.
'master' logs only on main process, 'collect'
broadcasts logs from workers to master and 'workers'
means each process will output its own log (default:
master)
Multi-task training
Theory
The multi-task training process can simultaneously handle different datasets with properties that cannot be fitted in one network (e.g. properties from DFT calculations under different exchange-correlation functionals or different basis sets). These datasets are denoted by \(\boldsymbol x^{(1)}, \dots, \boldsymbol x^{(n_t)}\). For each dataset, a training task is defined as
During the multi-task training process, all tasks share one descriptor with trainable parameters \(\boldsymbol{\theta}_ {d}\), while each of them has its own fitting network with trainable parameters \(\boldsymbol{\theta}_ f^{(t)}\), thus \(\boldsymbol{\theta}^{(t)} = \{ \boldsymbol{\theta}_ {d} , \boldsymbol{\theta}_ {f}^{(t)} \}\). At each training step, a task is randomly picked from \({1, \dots, n_t}\), and the Adam optimizer is executed to minimize \(L^{(t)}\) for one step to update the parameter \(\boldsymbol \theta^{(t)}\). If different fitting networks have the same architecture, they can share the parameters of some layers to improve training efficiency.1
Perform the multi-task training
Training on multiple data sets (each data set contains several data systems) can be performed in multi-task mode, with one common descriptor and multiple specific fitting nets for each data set. One can simply switch the following parameters in training input script to perform multi-task mode:
fitting_net –> fitting_net_dict, each key of which can be one individual fitting net.
training_data, validation_data –> data_dict, each key of which can be one individual data set contains several data systems for corresponding fitting net, the keys must be consistent with those in fitting_net_dict.
loss –> loss_dict, each key of which can be one individual loss setting for corresponding fitting net, the keys must be consistent with those in fitting_net_dict, if not set, the corresponding fitting net will use the default loss.
(Optional) fitting_weight, each key of which can be a non-negative integer or float, deciding the chosen probability for corresponding fitting net in training, if not set or invalid, the corresponding fitting net will not be used.
The training procedure will automatically choose single-task or multi-task mode, based on the above parameters. Note that parameters of single-task mode and multi-task mode can not be mixed.
An example input for training energy and dipole in water system can be found here: multi-task input on water.
The supported descriptors for multi-task mode are listed:
se_a (se_e2_a)
se_r (se_e2_r)
se_at (se_e3)
se_atten
se_atten_v2
hybrid
The supported fitting nets for multi-task mode are listed:
ener
dipole
polar
The output of dp freeze command in multi-task mode can be seen in freeze command.
Initialization from pretrained multi-task model
For advance training in multi-task mode, one can first train the descriptor on several upstream datasets and then transfer it on new downstream ones with newly added fitting nets. At the second step, you can also inherit some fitting nets trained on upstream datasets, by merely adding fitting net keys in fitting_net_dict and optional fitting net weights in fitting_weight.
Take multi-task input on water again for example. You can first train a multi-task model using input script with the following model part:
"model": {
"type_map": ["O", "H"],
"descriptor": {
"type": "se_e2_a",
"sel": [46, 92],
"rcut_smth": 0.5,
"rcut": 6.0,
"neuron": [25, 50, 100],
"type_one_side": true
},
"fitting_net_dict": {
"water_dipole": {
"type": "dipole",
"neuron": [100, 100, 100]
},
"water_ener": {
"neuron": [240, 240, 240],
"resnet_dt": true
}
},
}
After training, you can freeze this multi-task model into one unit graph:
$ dp freeze -o graph.pb --united-model
Then if you want to transfer the trained descriptor and some fitting nets (take water_ener for example) to newly added datasets with new fitting net water_ener_2, you can modify the model part of the new input script in a more simplified way:
"model": {
"type_map": ["O", "H"],
"descriptor": {},
"fitting_net_dict": {
"water_ener": {},
"water_ener_2": {
"neuron": [240, 240, 240],
"resnet_dt": true,
}
},
}
It will autocomplete the configurations according to the frozen graph.
Note that for newly added fitting net keys, other parts in the input script, including data_dict and loss_dict (optionally fitting_weight), should be set explicitly. While for old fitting net keys, it will inherit the old configurations if not set.
Finally, you can perform the modified multi-task training from the frozen model with command:
$ dp train input.json --init_frz_model graph.pb
TensorBoard Usage
TensorBoard provides the visualization and tooling needed for machine learning experimentation. Full instructions for TensorBoard can be found here.
Highlighted features
DeePMD-kit can now use most of the interesting features enabled by TensorBoard!
Tracking and visualizing metrics, such as l2_loss, l2_energy_loss and l2_force_loss
Visualizing the model graph (ops and layers)
Viewing histograms of weights, biases, or other tensors as they change over time.
Viewing summaries of trainable variables
How to use Tensorboard with DeePMD-kit
Before running TensorBoard, make sure you have generated summary data in a log directory by modifying the input script, setting tensorboard to true in the training subsection will enable the TensorBoard data analysis. eg. water_se_a.json.
"training" : {
"systems": ["../data/"],
"set_prefix": "set",
"stop_batch": 1000000,
"batch_size": 1,
"seed": 1,
"_comment": " display and restart",
"_comment": " frequencies counted in batch",
"disp_file": "lcurve.out",
"disp_freq": 100,
"numb_test": 10,
"save_freq": 1000,
"save_ckpt": "model.ckpt",
"disp_training":true,
"time_training":true,
"tensorboard": true,
"tensorboard_log_dir":"log",
"tensorboard_freq": 1000,
"profiling": false,
"profiling_file":"timeline.json",
"_comment": "that's all"
}
Once you have event files, run TensorBoard and provide the log directory. This should print that TensorBoard has started. Next, connect to http://tensorboard_server_ip:6006.
TensorBoard requires a logdir to read logs from. For info on configuring TensorBoard, run TensorBoard –help. One can easily change the log name with “tensorboard_log_dir” and the sampling frequency with “tensorboard_freq”.
tensorboard --logdir path/to/logs
Examples
Tracking and visualizing loss metrics(red:train, blue:test)



Visualizing DeePMD-kit model graph

Viewing histograms of weights, biases, or other tensors as they change over time


Viewing summaries of trainable variables

Attention
Allowing the tensorboard analysis will takes extra execution time.(eg, 15% increasing @Nvidia GTX 1080Ti double precision with default water sample)
TensorBoard can be used in Google Chrome or Firefox. Other browsers might work, but there may be bugs or performance issues.
Known limitations of using GPUs
If you use DeePMD-kit in a GPU environment, the acceptable value range of some variables is additionally restricted compared to the CPU environment due to the software’s GPU implementations:
The number of atom types of a given system must be less than 128.
The maximum distance between an atom and its neighbors must be less than 128. It can be controlled by setting the rcut value of training parameters.
Theoretically, the maximum number of atoms that a single GPU can accept is about 10,000,000. However, this value is limited by the GPU memory size currently, usually within 1000,000 atoms even in the model compression mode.
The total sel value of training parameters(in
model/descriptorsection) must be less than 4096.The size of the last layer of the embedding net must be less than 1024 during the model compression process.
Finetune the pretrained model
Pretraining-and-finetuning is a widely used approach in other fields such as Computer Vision (CV) or Natural Language Processing (NLP) to vastly reduce the training cost, while it’s not trivial in potential models. Compositions and configurations of data samples or even computational parameters in upstream software (such as VASP) may be different between the pretrained and target datasets, leading to energy shifts or other diversities of training data.
Recently the emerging of methods such as DPA-1 has brought us to a new stage where we can perform similar pretraining-finetuning approaches. DPA-1 can hopefully learn the common knowledge in the pretrained dataset (especially the force information) and thus reduce the computational cost in downstream training tasks. If you have a pretrained model pretrained.pb (here we support models using se_atten descriptor and ener fitting net) on a large dataset (for example, OC2M in DPA-1 paper), a finetuning strategy can be performed by simply running:
$ dp train input.json --finetune pretrained.pb
The command above will change the energy bias in the last layer of the fitting net in pretrained.pb, according to the training dataset in input.json.
Warning
Note that the elements in the training dataset must be contained in the pretrained dataset.
The finetune procedure will inherit the model structures in pretrained.pb, and thus it will ignore the model parameters in input.json, such as descriptor, fitting_net, type_embedding and type_map. However, you can still set the trainable parameters in each part of input.json to control the training procedure.
To obtain a more simplified script, for example, you can change the model part in input.json to perform finetuning:
"model": {
"type_map": ["O", "H"],
"type_embedding": {"trainable": true},
"descriptor" : {},
"fitting_net" : {}
}
Freeze and Compress
Freeze a model
The trained neural network is extracted from a checkpoint and dumped into a protobuf(.pb) file. This process is called “freezing” a model. The idea and part of our code are from Morgan. To freeze a model, typically one does
$ dp freeze -o graph.pb
in the folder where the model is trained. The output model is called graph.pb.
In multi-task mode:
This process will in default output several models, each of which contains the common descriptor and one of the user-defined fitting nets in fitting_net_dict, let’s name it
fitting_key, together frozen ingraph_{fitting_key}.pb. Those frozen models are exactly the same as single-task output with fitting netfitting_key.If you add
--united-modeloption in this situation, the total multi-task model will be frozen into one unitgraph.pb, which is mainly for multi-task initialization and can not be used directly for inference.
Compress a model
Theory
The compression of the DP model uses three techniques, tabulated inference, operator merging, and precise neighbor indexing, to improve the performance of model training and inference when the model parameters are properly trained.
For better performance, the NN inference can be replaced by tabulated function evaluations if the input of the NN is of dimension one. The idea is to approximate the output of the NN by a piece-wise polynomial fitting. The input domain (a compact domain in \(\mathbb R\)) is divided into \(L_c\) equally spaced intervals, in which we apply a fifth-order polynomial \(g^l_m(x)\) approximation of the \(m\)-th output component of the NN function:
where \(l=1,2,\dots,L_c\) is the index of the intervals, \(x_1, \dots, x_{L_c}, x_{L_c+1}\) are the endpoints of the intervals, and \(a^l_m\), \(b^l_m\), \(c^l_m\), \(d^l_m\), \(e^l_m\), and \(f^l_m\) are the fitting parameters. The fitting parameters can be computed by the equations below:
where \(\Delta x_l=x_{l+1}-x_l\) denotes the size of the interval. \(h_{m,l}=y_{m,l+1}-y_{m,l}\). \(y_{m,l} = y_m(x_l)\), \(y'_{m,l} = y'_m(x_l)\) and \(y''_{m,l} = y''_m(x_l)\) are the value, the first-order derivative, and the second-order derivative of the \(m\)-th component of the target NN function at the interval point \(x_l\), respectively. The first and second-order derivatives are easily calculated by the back-propagation of the NN functions.
In the standard DP model inference, taking the two-body embedding descriptor as an example, the matrix product \((\mathcal G^i)^T \mathcal R\) requires the transfer of the tensor \(\mathcal G^i\) between the register and the host/device memories, which usually becomes the bottle-neck of the computation due to the relatively small memory bandwidth of the GPUs. The compressed DP model merges the matrix multiplication \((\mathcal G^i)^T \mathcal R\) with the tabulated inference step. More specifically, once one column of the \((\mathcal G^i)^T\) is evaluated, it is immediately multiplied with one row of the environment matrix in the register, and the outer product is deposited to the result of \((\mathcal G^i)^T \mathcal R\). By the operator merging technique, the allocation of \(\mathcal G^i\) and the memory movement between register and host/device memories is avoided. The operator merging of the three-body embedding can be derived analogously.
The first dimension, \(N_c\), of the environment (\(\mathcal R^i\)) and embedding (\(\mathcal G^i\)) matrices is the expected maximum number of neighbors. If the number of neighbors of an atom is smaller than \(N_c\), the corresponding positions of the matrices are pad with zeros. In practice, if the real number of neighbors is significantly smaller than \(N_c\), a notable operation is spent on the multiplication of padding zeros. In the compressed DP model, the number of neighbors is precisely indexed at the tabulated inference stage, further saving computational costs.1
Instructions
Once the frozen model is obtained from DeePMD-kit, we can get the neural network structure and its parameters (weights, biases, etc.) from the trained model, and compress it in the following way:
dp compress -i graph.pb -o graph-compress.pb
where -i gives the original frozen model, -o gives the compressed model. Several other command line options can be passed to dp compress, which can be checked with
$ dp compress --help
An explanation will be provided
usage: dp compress [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-m {master,collect,workers}] [-i INPUT] [-o OUTPUT]
[-s STEP] [-e EXTRAPOLATE] [-f FREQUENCY]
[-c CHECKPOINT_FOLDER]
optional arguments:
-h, --help show this help message and exit
-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}, --log-level {DEBUG,3,INFO,2,WARNING,1,ERROR,0}
set verbosity level by string or number, 0=ERROR,
1=WARNING, 2=INFO and 3=DEBUG (default: INFO)
-l LOG_PATH, --log-path LOG_PATH
set log file to log messages to disk, if not
specified, the logs will only be output to console
(default: None)
-m {master,collect,workers}, --mpi-log {master,collect,workers}
Set the manner of logging when running with MPI.
'master' logs only on main process, 'collect'
broadcasts logs from workers to master and 'workers'
means each process will output its own log (default:
master)
-i INPUT, --input INPUT
The original frozen model, which will be compressed by
the code (default: frozen_model.pb)
-o OUTPUT, --output OUTPUT
The compressed model (default:
frozen_model_compressed.pb)
-s STEP, --step STEP Model compression uses fifth-order polynomials to
interpolate the embedding-net. It introduces two
tables with different step size to store the
parameters of the polynomials. The first table covers
the range of the training data, while the second table
is an extrapolation of the training data. The domain
of each table is uniformly divided by a given step
size. And the step(parameter) denotes the step size of
the first table and the second table will use 10 *
step as it's step size to save the memory. Usually the
value ranges from 0.1 to 0.001. Smaller step means
higher accuracy and bigger model size (default: 0.01)
-e EXTRAPOLATE, --extrapolate EXTRAPOLATE
The domain range of the first table is automatically
detected by the code: [d_low, d_up]. While the second
table ranges from the first table's upper
boundary(d_up) to the extrapolate(parameter) * d_up:
[d_up, extrapolate * d_up] (default: 5)
-f FREQUENCY, --frequency FREQUENCY
The frequency of tabulation overflow check(Whether the
input environment matrix overflow the first or second
table range). By default do not check the overflow
(default: -1)
-c CHECKPOINT_FOLDER, --checkpoint-folder CHECKPOINT_FOLDER
path to checkpoint folder (default: .)
-t TRAINING_SCRIPT, --training-script TRAINING_SCRIPT
The training script of the input frozen model
(default: None)
Parameter explanation
Model compression, which includes tabulating the embedding net. The table is composed of fifth-order polynomial coefficients and is assembled from two sub-tables. For model descriptor with se_e2_a type, the first sub-table takes the stride(parameter) as its uniform stride, while the second sub-table takes 10 _ stride as its uniform stride; For model descriptor with se_e3 type, the first sub-table takes 10 _ stride as it’s uniform stride, while the second sub-table takes 100 _ stride as it’s uniform stride. The range of the first table is automatically detected by DeePMD-kit, while the second table ranges from the first table’s upper boundary(upper) to the extrapolate(parameter) _ upper. Finally, we added a check frequency parameter. It indicates how often the program checks for overflow(if the input environment matrix overflows the first or second table range) during the MD inference.
Justification of model compression
Model compression, with little loss of accuracy, can greatly speed up MD inference time. According to different simulation systems and training parameters, the speedup can reach more than 10 times at both CPU and GPU devices. At the same time, model compression can greatly change memory usage, reducing as much as 20 times under the same hardware conditions.
Acceptable original model version
The model compression interface requires the version of DeePMD-kit used in the original model generation should be 2.0.0-alpha.0 or above. If one has a frozen 1.2 or 1.3 model, one can upgrade it through the dp convert-from interface. (eg: dp convert-from 1.2/1.3 -i old_frozen_model.pb -o new_frozen_model.pb)
Acceptable descriptor type
Descriptors with se_e2_a, se_e3, se_e2_r and se_atten_v2 types are supported by the model compression feature. Hybrid mixed with the above descriptors is also supported.
Available activation functions for descriptor:
tanh
gelu
relu
relu6
softplus
sigmoid
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Test
Test a model
The frozen model can be used in many ways. The most straightforward test can be performed using dp test. A typical usage of dp test is
dp test -m graph.pb -s /path/to/system -n 30
where -m gives the tested model, -s the path to the tested system and -n the number of tested frames. Several other command line options can be passed to dp test, which can be checked with
$ dp test --help
An explanation will be provided
usage: dp test [-h] [-m MODEL] [-s SYSTEM] [-S SET_PREFIX] [-n NUMB_TEST]
[-r RAND_SEED] [--shuffle-test] [-d DETAIL_FILE]
optional arguments:
-h, --help show this help message and exit
-m MODEL, --model MODEL
Frozen model file to import
-s SYSTEM, --system SYSTEM
The system dir
-S SET_PREFIX, --set-prefix SET_PREFIX
The set prefix
-n NUMB_TEST, --numb-test NUMB_TEST
The number of data for test
-r RAND_SEED, --rand-seed RAND_SEED
The random seed
--shuffle-test Shuffle test data
-d DETAIL_FILE, --detail-file DETAIL_FILE
The prefix to files where details of energy, force and virial accuracy/accuracy per atom will be written
-a, --atomic Test the accuracy of atomic label, i.e. energy / tensor (dipole, polar)
Calculate Model Deviation
Theory
Model deviation \(\epsilon_y\) is the standard deviation of properties \(\boldsymbol y\) inferred by an ensemble of models \(\mathcal{M}_ 1, \dots, \mathcal{M}_{n_m}\) that are trained by the same dataset(s) with the model parameters initialized independently. The DeePMD-kit supports \(\boldsymbol y\) to be the atomic force \(\boldsymbol F_i\) and the virial tensor \(\boldsymbol \Xi\). The model deviation is used to estimate the error of a model at a certain data frame, denoted by \(\boldsymbol x\), containing the coordinates and chemical species of all atoms. We present the model deviation of the atomic force and the virial tensor
where \(\boldsymbol \theta_k\) is the parameters of the model \(\mathcal M_k\), and the ensemble average \(\langle\cdot\rangle\) is estimated by
Small \(\epsilon_{\boldsymbol{F},i}\) means the model has learned the given data; otherwise, it is not covered, and the training data needs to be expanded. If the magnitude of \(\boldsymbol F_i\) or \(\boldsymbol \Xi\) is quite large, a relative model deviation \(\epsilon_{\boldsymbol{F},i,\text{rel}}\) or \(\epsilon_{\boldsymbol{\Xi},\alpha\beta,\text{rel}}\) can be used instead of the absolute model deviation:
where \(\nu\) is a small constant used to protect an atom where the magnitude of \(\boldsymbol{F}_i\) or \(\boldsymbol{\Xi}\) is small from having a large model deviation.
Statistics of \(\epsilon_{\boldsymbol{F},i}\) and \(\epsilon_{\boldsymbol{\Xi},{\alpha \beta}}\) can be provided, including the maximum, average, and minimal model deviation over the atom index \(i\) and over the component index \(\alpha,\beta\), respectively. The maximum model deviation of forces \(\epsilon_{\boldsymbol F,\text{max}}\) in a frame was found to be the best error indicator in a concurrent or active learning algorithm.1
Instructions
One can also use a subcommand to calculate the deviation of predicted forces or virials for a bunch of models in the following way:
dp model-devi -m graph.000.pb graph.001.pb graph.002.pb graph.003.pb -s ./data -o model_devi.out
where -m specifies graph files to be calculated, -s gives the data to be evaluated, -o the file to which model deviation results is dumped. Here is more information on this sub-command:
usage: dp model-devi [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}]
[-l LOG_PATH] [-m MODELS [MODELS ...]] [-s SYSTEM]
[-S SET_PREFIX] [-o OUTPUT] [-f FREQUENCY] [-i ITEMS]
optional arguments:
-h, --help show this help message and exit
-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}, --log-level {DEBUG,3,INFO,2,WARNING,1,ERROR,0}
set verbosity level by string or number, 0=ERROR,
1=WARNING, 2=INFO and 3=DEBUG (default: INFO)
-l LOG_PATH, --log-path LOG_PATH
set log file to log messages to disk, if not
specified, the logs will only be output to console
(default: None)
-m MODELS [MODELS ...], --models MODELS [MODELS ...]
Frozen models file to import (default:
['graph.000.pb', 'graph.001.pb', 'graph.002.pb',
'graph.003.pb'])
-s SYSTEM, --system SYSTEM
The system directory, not support recursive detection.
(default: .)
-S SET_PREFIX, --set-prefix SET_PREFIX
The set prefix (default: set)
-o OUTPUT, --output OUTPUT
The output file for results of model deviation
(default: model_devi.out)
-f FREQUENCY, --frequency FREQUENCY
The trajectory frequency of the system (default: 1)
For more details concerning the definition of model deviation and its application, please refer to Yuzhi Zhang, Haidi Wang, Weijie Chen, Jinzhe Zeng, Linfeng Zhang, Han Wang, and Weinan E, DP-GEN: A concurrent learning platform for the generation of reliable deep learning based potential energy models, Computer Physics Communications, 2020, 253, 107206.
Relative model deviation
By default, the model deviation is output in absolute value. If the argument --relative is passed, then the relative model deviation of the force will be output, including values output by the argument --atomic. The relative model deviation of the force on atom \(i\) is defined by
where \(D_{f_i}\) is the absolute model deviation of the force on atom \(i\), \(f_i\) is the norm of the force and \(l\) is provided as the parameter of the keyword relative. If the argument --relative_v is set, then the relative model deviation of the virial will be output instead of the absolute value, with the same definition of that of the force:
- 1
This section is built upon Jinzhe Zeng, Duo Zhang, Denghui Lu, Pinghui Mo, Zeyu Li, Yixiao Chen, Marián Rynik, Li’ang Huang, Ziyao Li, Shaochen Shi, Yingze Wang, Haotian Ye, Ping Tuo, Jiabin Yang, Ye Ding, Yifan Li, Davide Tisi, Qiyu Zeng, Han Bao, Yu Xia, Jiameng Huang, Koki Muraoka, Yibo Wang, Junhan Chang, Fengbo Yuan, Sigbjørn Løland Bore, Chun Cai, Yinnian Lin, Bo Wang, Jiayan Xu, Jia-Xin Zhu, Chenxing Luo, Yuzhi Zhang, Rhys E. A. Goodall, Wenshuo Liang, Anurag Kumar Singh, Sikai Yao, Jingchao Zhang, Renata Wentzcovitch, Jiequn Han, Jie Liu, Weile Jia, Darrin M. York, Weinan E, Roberto Car, Linfeng Zhang, Han Wang, J. Chem. Phys. 159, 054801 (2023) licensed under a Creative Commons Attribution (CC BY) license.
Inference
Note that the model for inference is required to be compatible with the DeePMD-kit package. See Model compatibility for details.
Python interface
One may use the python interface of DeePMD-kit for model inference, an example is given as follows
from deepmd.infer import DeepPot
import numpy as np
dp = DeepPot("graph.pb")
coord = np.array([[1, 0, 0], [0, 0, 1.5], [1, 0, 3]]).reshape([1, -1])
cell = np.diag(10 * np.ones(3)).reshape([1, -1])
atype = [1, 0, 1]
e, f, v = dp.eval(coord, cell, atype)
where e, f and v are predicted energy, force and virial of the system, respectively.
Furthermore, one can use the python interface to calculate model deviation.
from deepmd.infer import calc_model_devi
from deepmd.infer import DeepPot as DP
import numpy as np
coord = np.array([[1, 0, 0], [0, 0, 1.5], [1, 0, 3]]).reshape([1, -1])
cell = np.diag(10 * np.ones(3)).reshape([1, -1])
atype = [1, 0, 1]
graphs = [DP("graph.000.pb"), DP("graph.001.pb")]
model_devi = calc_model_devi(coord, cell, atype, graphs)
Note that if the model inference or model deviation is performed cyclically, one should avoid calling the same model multiple times. Otherwise, tensorFlow will never release the memory and this may lead to an out-of-memory (OOM) error.
External neighbor list algorithm
The native neighbor list algorithm of the DeePMD-kit is in \(O(N^2)\) complexity (\(N\) is the number of atoms). While this is not a problem for small systems that quantum methods can afford, the large systems for molecular dynamics have slow performance. In this case, one may pass an external neighbor list that has lower complexity to DeepPot, once it is compatible with ase.neighborlist.NewPrimitiveNeighborList.
import ase.neighborlist
neighbor_list = ase.neighborlist.NewPrimitiveNeighborList(
cutoffs=6, bothways=True, self_interaction=False
)
dp = DeepPot("graph.pb", neighbor_list=neighbor_list)
The update and build methods will be called by DeepPot, and first_neigh, pair_second, and offset_vec properties will be used.
C/C++ interface
C++ interface
The C++ interface of DeePMD-kit is also available for the model interface, which is considered faster than the Python interface. An example infer_water.cpp is given below:
#include "deepmd/DeepPot.h"
int main(){
deepmd::DeepPot dp ("graph.pb");
std::vector<double > coord = {1., 0., 0., 0., 0., 1.5, 1. ,0. ,3.};
std::vector<double > cell = {10., 0., 0., 0., 10., 0., 0., 0., 10.};
std::vector<int > atype = {1, 0, 1};
double e;
std::vector<double > f, v;
dp.compute (e, f, v, coord, atype, cell);
}
where e, f and v are predicted energy, force and virial of the system, respectively. See deepmd::DeepPot for details.
You can compile infer_water.cpp using gcc:
gcc infer_water.cpp -L $deepmd_root/lib -L $tensorflow_root/lib -I $deepmd_root/include -Wl,--no-as-needed -ldeepmd_cc -lstdc++ -ltensorflow_cc -Wl,-rpath=$deepmd_root/lib -Wl,-rpath=$tensorflow_root/lib -o infer_water
and then run the program:
./infer_water
C interface
Although C is harder to write, the C library will not be affected by different versions of C++ compilers.
An example infer_water.c is given below:
#include <stdio.h>
#include <stdlib.h>
#include "deepmd/c_api.h"
int main(){
const char* model = "graph.pb";
double coord[] = {1., 0., 0., 0., 0., 1.5, 1. ,0. ,3.};
double cell[] = {10., 0., 0., 0., 10., 0., 0., 0., 10.};
int atype[] = {1, 0, 1};
// init C pointers with given memory
double* e = malloc(sizeof(*e));
double* f = malloc(sizeof(*f) * 9); // natoms * 3
double* v = malloc(sizeof(*v) * 9);
double* ae = malloc(sizeof(*ae) * 9); // natoms
double* av = malloc(sizeof(*av) * 27); // natoms * 9
// DP model
DP_DeepPot* dp = DP_NewDeepPot(model);
DP_DeepPotCompute (dp, 3, coord, atype, cell, e, f, v, ae, av);
// print results
printf("energy: %f\n", *e);
for (int ii = 0; ii < 9; ++ii)
printf("force[%d]: %f\n", ii, f[ii]);
for (int ii = 0; ii < 9; ++ii)
printf("force[%d]: %f\n", ii, v[ii]);
// free memory
free(e);
free(f);
free(v);
free(ae);
free(av);
DP_DeleteDeepPot(dp);
}
where e, f and v are predicted energy, force and virial of the system, respectively. ae and av are atomic energy and atomic virials, respectively. See DP_DeepPotCompute() for details.
You can compile infer_water.c using gcc:
gcc infer_water.c -L $deepmd_root/lib -L $tensorflow_root/lib -I $deepmd_root/include -Wl,--no-as-needed -ldeepmd_c -Wl,-rpath=$deepmd_root/lib -Wl,-rpath=$tensorflow_root/lib -o infer_water
and then run the program:
./infer_water
Header-only C++ library interface (recommended)
The header-only C++ library is built based on the C library. Thus, it has the same ABI compatibility as the C library but provides a powerful C++ interface. To use it, include deepmd/deepmd.hpp.
#include "deepmd/deepmd.hpp"
int main(){
deepmd::hpp::DeepPot dp ("graph.pb");
std::vector<double > coord = {1., 0., 0., 0., 0., 1.5, 1. ,0. ,3.};
std::vector<double > cell = {10., 0., 0., 0., 10., 0., 0., 0., 10.};
std::vector<int > atype = {1, 0, 1};
double e;
std::vector<double > f, v;
dp.compute (e, f, v, coord, atype, cell);
}
Note that the feature of the header-only C++ library is still limited compared to the original C++ library. See deepmd::hpp::DeepPot for details.
You can compile infer_water_hpp.cpp using gcc:
gcc infer_water_hpp.cpp -L $deepmd_root/lib -L $tensorflow_root/lib -I $deepmd_root/include -Wl,--no-as-needed -ldeepmd_c -Wl,-rpath=$deepmd_root/lib -Wl,-rpath=$tensorflow_root/lib -o infer_water_hpp
and then run the program:
./infer_water_hpp
In some cases, one may want to pass the custom neighbor list instead of the native neighbor list. The above code can be revised as follows:
// neighbor list
std::vector<std::vector<int >> nlist_vec = {
{1, 2},
{0, 2},
{0, 1}
};
std::vector<int> ilist(3), numneigh(3);
std::vector<int*> firstneigh(3);
InputNlist nlist(3, &ilist[0], &numneigh[0], &firstneigh[0]);
convert_nlist(nlist, nlist_vec);
dp.compute (e, f, v, coord, atype, cell, 0, nlist, 0);
Here, nlist_vec means the neighbors of atom 0 are atom 1 and atom 2, the neighbors of atom 1 are atom 0 and atom 2, and the neighbors of atom 2 are atom 0 and atom 1.
Node.js interface
If Node.js interface is installed, one can use the Node.js interface for model inference, which is a wrapper of the header-only C++ API.
A simple example is shown below.
const deepmd = require("deepmd-kit");
const dp = new deepmd.DeepPot("graph.pb");
const coord = [1, 0, 0, 0, 0, 1.5, 1, 0, 3];
const atype = [1, 0, 1];
const cell = [10, 0, 0, 0, 10, 0, 0, 0, 10];
const v_coord = new deepmd.vectord(coord.length);
const v_atype = new deepmd.vectori(atype.length);
const v_cell = new deepmd.vectord(cell.length);
for (var i = 0; i < coord.length; i++) v_coord.set(i, coord[i]);
for (var i = 0; i < atype.length; i++) v_atype.set(i, atype[i]);
for (var i = 0; i < cell.length; i++) v_cell.set(i, cell[i]);
var energy = 0.0;
var v_forces = new deepmd.vectord();
var v_virials = new deepmd.vectord();
energy = dp.compute(energy, v_forces, v_virials, v_coord, v_atype, v_cell);
console.log("energy:", energy);
console.log(
"forces:",
[...Array(v_forces.size()).keys()].map((i) => v_forces.get(i)),
);
console.log(
"virials:",
[...Array(v_virials.size()).keys()].map((i) => v_virials.get(i)),
);
Energy, forces, and virials will be printed to the screen.
Command line interface
DeePMD-kit: A deep learning package for many-body potential energy representation and molecular dynamics
usage: dp [-h] [--version]
{transfer,train,freeze,test,compress,doc-train-input,model-devi,convert-from,neighbor-stat,train-nvnmd,gui}
...
Named Arguments
- --version
show program’s version number and exit
Valid subcommands
- command
Possible choices: transfer, train, freeze, test, compress, doc-train-input, model-devi, convert-from, neighbor-stat, train-nvnmd, gui
Sub-commands
transfer
pass parameters to another model
dp transfer [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-r RAW_MODEL] [-O OLD_MODEL] [-o OUTPUT]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -r, --raw-model
the model receiving parameters
Default: “raw_frozen_model.pb”
- -O, --old-model
the model providing parameters
Default: “old_frozen_model.pb”
- -o, --output
the model after passing parameters
Default: “frozen_model.pb”
train
train a model
dp train [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-m {master,collect,workers}]
[-i INIT_MODEL | -r RESTART | -f INIT_FRZ_MODEL | -t FINETUNE]
[-o OUTPUT] [--skip-neighbor-stat]
INPUT
Positional Arguments
- INPUT
the input parameter file in json or yaml format
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -m, --mpi-log
Possible choices: master, collect, workers
Set the manner of logging when running with MPI. ‘master’ logs only on main process, ‘collect’ broadcasts logs from workers to master and ‘workers’ means each process will output its own log
Default: “master”
- -i, --init-model
Initialize the model by the provided path prefix of checkpoint files.
- -r, --restart
Restart the training from the provided path prefix of checkpoint files.
- -f, --init-frz-model
Initialize the training from the frozen model.
- -t, --finetune
Finetune the frozen pretrained model.
- -o, --output
The output file of the parameters used in training.
Default: “out.json”
- --skip-neighbor-stat
Skip calculating neighbor statistics. Sel checking, automatic sel, and model compression will be disabled.
Default: False
- examples:
dp train input.json dp train input.json –restart model.ckpt dp train input.json –init-model model.ckpt
freeze
freeze the model
dp freeze [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-c CHECKPOINT_FOLDER] [-o OUTPUT] [-n NODE_NAMES] [-w NVNMD_WEIGHT]
[--united-model]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -c, --checkpoint-folder
Path to checkpoint, either a folder containing checkpoint or the checkpoint prefix
Default: “.”
- -o, --output
name of graph, will output to the checkpoint folder
Default: “frozen_model.pb”
- -n, --node-names
the frozen nodes, if not set, determined from the model type
- -w, --nvnmd-weight
the name of weight file (.npy), if set, save the model’s weight into the file
- --united-model
When in multi-task mode, freeze all nodes into one united model
Default: False
- examples:
dp freeze dp freeze -o graph.pb
test
test the model
dp test [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH] [-m MODEL]
[-s SYSTEM | -f DATAFILE] [-S SET_PREFIX] [-n NUMB_TEST]
[-r RAND_SEED] [--shuffle-test] [-d DETAIL_FILE] [-a]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -m, --model
Frozen model file to import
Default: “frozen_model.pb”
- -s, --system
The system dir. Recursively detect systems in this directory
Default: “.”
- -f, --datafile
The path to file of test list.
- -S, --set-prefix
The set prefix
Default: “set”
- -n, --numb-test
The number of data for test. 0 means all data.
Default: 0
- -r, --rand-seed
The random seed
- --shuffle-test
Shuffle test data
Default: False
- -d, --detail-file
The prefix to files where details of energy, force and virial accuracy/accuracy per atom will be written
- -a, --atomic
Test the accuracy of atomic label, i.e. energy / tensor (dipole, polar)
Default: False
- examples:
dp test -m graph.pb -s /path/to/system -n 30
compress
compress a model
dp compress [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-m {master,collect,workers}] [-i INPUT] [-o OUTPUT] [-s STEP]
[-e EXTRAPOLATE] [-f FREQUENCY] [-c CHECKPOINT_FOLDER]
[-t TRAINING_SCRIPT]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -m, --mpi-log
Possible choices: master, collect, workers
Set the manner of logging when running with MPI. ‘master’ logs only on main process, ‘collect’ broadcasts logs from workers to master and ‘workers’ means each process will output its own log
Default: “master”
- -i, --input
The original frozen model, which will be compressed by the code
Default: “frozen_model.pb”
- -o, --output
The compressed model
Default: “frozen_model_compressed.pb”
- -s, --step
Model compression uses fifth-order polynomials to interpolate the embedding-net. It introduces two tables with different step size to store the parameters of the polynomials. The first table covers the range of the training data, while the second table is an extrapolation of the training data. The domain of each table is uniformly divided by a given step size. And the step(parameter) denotes the step size of the first table and the second table will use 10 * step as it’s step size to save the memory. Usually the value ranges from 0.1 to 0.001. Smaller step means higher accuracy and bigger model size
Default: 0.01
- -e, --extrapolate
The domain range of the first table is automatically detected by the code: [d_low, d_up]. While the second table ranges from the first table’s upper boundary(d_up) to the extrapolate(parameter) * d_up: [d_up, extrapolate * d_up]
Default: 5
- -f, --frequency
The frequency of tabulation overflow check(Whether the input environment matrix overflow the first or second table range). By default do not check the overflow
Default: -1
- -c, --checkpoint-folder
path to checkpoint folder
Default: “model-compression”
- -t, --training-script
The training script of the input frozen model
- examples:
dp compress dp compress -i graph.pb -o compressed.pb
doc-train-input
print the documentation (in rst format) of input training parameters.
dp doc-train-input [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[--out-type {rst,json}]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- --out-type
Possible choices: rst, json
The output type
Default: “rst”
model-devi
calculate model deviation
dp model-devi [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-m MODELS [MODELS ...]] [-s SYSTEM] [-S SET_PREFIX] [-o OUTPUT]
[-f FREQUENCY] [--real_error] [--atomic] [--relative RELATIVE]
[--relative_v RELATIVE_V]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -m, --models
Frozen models file to import
Default: [‘graph.000.pb’, ‘graph.001.pb’, ‘graph.002.pb’, ‘graph.003.pb’]
- -s, --system
The system directory. Recursively detect systems in this directory.
Default: “.”
- -S, --set-prefix
The set prefix
Default: “set”
- -o, --output
The output file for results of model deviation
Default: “model_devi.out”
- -f, --frequency
The trajectory frequency of the system
Default: 1
- --real_error
Calculate the RMS real error of the model. The real data should be given in the systems.
Default: False
- --atomic
Print the force model deviation of each atom.
Default: False
- --relative
Calculate the relative model deviation of force. The level parameter for computing the relative model deviation of the force should be given.
- --relative_v
Calculate the relative model deviation of virial. The level parameter for computing the relative model deviation of the virial should be given.
- examples:
dp model-devi -m graph.000.pb graph.001.pb graph.002.pb graph.003.pb -s ./data -o model_devi.out
convert-from
convert lower model version to supported version
dp convert-from [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-i INPUT_MODEL] [-o OUTPUT_MODEL]
[{auto,0.12,1.0,1.1,1.2,1.3,2.0,pbtxt}]
Positional Arguments
- FROM
Possible choices: auto, 0.12, 1.0, 1.1, 1.2, 1.3, 2.0, pbtxt
The original model compatibility
Default: “auto”
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -i, --input-model
the input model
Default: “frozen_model.pb”
- -o, --output-model
the output model If OUTPUT_MODEL ends with ‘.pbtxt’, the provided model will be converted to pbtxt format, without version conversion.
Default: “convert_out.pb”
- examples:
dp convert-from -i graph.pb -o graph_new.pb dp convert-from auto -i graph.pb -o graph_new.pb dp convert-from 1.0 -i graph.pb -o graph_new.pb
neighbor-stat
Calculate neighbor statistics
dp neighbor-stat [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-s SYSTEM] -r RCUT -t TYPE_MAP [TYPE_MAP ...] [--one-type]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -s, --system
The system dir. Recursively detect systems in this directory
Default: “.”
- -r, --rcut
cutoff radius
- -t, --type-map
type map
- --one-type
treat all types as a single type. Used with se_atten descriptor.
Default: False
- examples:
dp neighbor-stat -s data -r 6.0 -t O H
train-nvnmd
train nvnmd model
dp train-nvnmd [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH]
[-i INIT_MODEL] [-r RESTART] [-s {s1,s2}]
[--skip-neighbor-stat]
INPUT
Positional Arguments
- INPUT
the input parameter file in json format
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -i, --init-model
Initialize the model by the provided path prefix of checkpoint files.
- -r, --restart
Restart the training from the provided prefix of checkpoint files.
- -s, --step
Possible choices: s1, s2
steps to train model of NVNMD: s1 (train CNN), s2 (train QNN)
Default: “s1”
- --skip-neighbor-stat
Skip calculating neighbor statistics. Sel checking, automatic sel, and model compression will be disabled.
Default: False
- examples:
dp train-nvnmd input_cnn.json -s s1 dp train-nvnmd input_qnn.json -s s2 dp train-nvnmd input_cnn.json -s s1 –restart model.ckpt dp train-nvnmd input_cnn.json -s s2 –init-model model.ckpt
gui
Serve DP-GUI.
dp gui [-h] [-v {DEBUG,3,INFO,2,WARNING,1,ERROR,0}] [-l LOG_PATH] [-p PORT]
[--bind_all]
Named Arguments
- -v, --log-level
Possible choices: DEBUG, 3, INFO, 2, WARNING, 1, ERROR, 0
set verbosity level by string or number, 0=ERROR, 1=WARNING, 2=INFO and 3=DEBUG
Default: “INFO”
- -l, --log-path
set log file to log messages to disk, if not specified, the logs will only be output to console
- -p, --port
The port to serve DP-GUI on.
Default: 6042
- --bind_all
Serve on all public interfaces. This will expose your DP-GUI instance to the network on both IPv4 and IPv6 (where available).
Default: False
Integrate with third-party packages
Note that the model for inference is required to be compatible with the DeePMD-kit package. See Model compatibility for details.
Use deep potential with ASE
Deep potential can be set up as a calculator with ASE to obtain potential energies and forces.
from ase import Atoms
from deepmd.calculator import DP
water = Atoms(
"H2O",
positions=[(0.7601, 1.9270, 1), (1.9575, 1, 1), (1.0, 1.0, 1.0)],
cell=[100, 100, 100],
calculator=DP(model="frozen_model.pb"),
)
print(water.get_potential_energy())
print(water.get_forces())
Optimization is also available:
from ase.optimize import BFGS
dyn = BFGS(water)
dyn.run(fmax=1e-6)
print(water.get_positions())
Run MD with LAMMPS
units
All units in LAMMPS except lj are supported. lj is not supported.
The most commonly used units are metal, since the internal units of distance, energy, force, and charge in DeePMD-kit are \AA, eV, eV / \AA, and proton charge, respectively. These units are consistent with the metal units in LAMMPS.
If one wants to use other units like real or si, it is welcome to do so. There is no need to do the unit conversion mannualy. The unit conversion is done automatically by LAMMPS.
The only thing that one needs to take care is the unit of the output of compute deeptensor/atom. Working with metal units for compute deeptensor/atom is totally fine, since there is no unit conversion. For other unit styles, we currently assume that the output of the compute deeptensor/atom command has the unit of distance and have applied the unit conversion factor of distance. If a user wants to infer quantities with units other than distance, the user is encouraged to open a GitHub feature request, so that the unit conversion factor can be added.
Enable DeePMD-kit plugin (plugin mode)
If you are using the plugin mode, enable DeePMD-kit package in LAMMPS with plugin command:
plugin load libdeepmd_lmp.so
After LAMMPS version patch_24Mar2022, another way to load plugins is to set the environmental variable LAMMPS_PLUGIN_PATH:
LAMMPS_PLUGIN_PATH=$deepmd_root/lib/deepmd_lmp
where $deepmd_root is the directory to install C++ interface.
The built-in mode doesn’t need this step.
pair_style deepmd
The DeePMD-kit package provides the pair_style deepmd
pair_style deepmd models ... keyword value ...
deepmd = style of this pair_style
models = frozen model(s) to compute the interaction. If multiple models are provided, then only the first model serves to provide energy and force prediction for each timestep of molecular dynamics, and the model deviation will be computed among all models every
out_freqtimesteps.keyword = out_file or out_freq or fparam or fparam_from_compute or aparam_from_compute or atomic or relative or relative_v or aparam or ttm
out_file value = filename
filename = The file name for the model deviation output. Default is model_devi.out
out_freq value = freq
freq = Frequency for the model deviation output. Default is 100.
fparam value = parameters
parameters = one or more frame parameters required for model evaluation.
fparam_from_compute value = id
id = compute id used to update the frame parameter.
aparam_from_compute value = id
id = compute id used to update the atom parameter.
atomic = no value is required.
If this keyword is set, the force model deviation of each atom will be output.
relative value = level
level = The level parameter for computing the relative model deviation of the force
relative_v value = level
level = The level parameter for computing the relative model deviation of the virial
aparam value = parameters
parameters = one or more atomic parameters of each atom required for model evaluation
ttm value = id
id = fix ID of fix ttm
Examples
pair_style deepmd graph.pb
pair_style deepmd graph.pb fparam 1.2
pair_style deepmd graph_0.pb graph_1.pb graph_2.pb out_file md.out out_freq 10 atomic relative 1.0
pair_coeff * * O H
pair_style deepmd cp.pb fparam_from_compute TEMP
compute TEMP all temp
pair_style deepmd ener.pb aparam_from_compute 1
compute 1 all ke/atom
Description
Evaluate the interaction of the system by using Deep Potential or Deep Potential Smooth Edition. It is noticed that deep potential is not a “pairwise” interaction, but a multi-body interaction.
This pair style takes the deep potential defined in a model file that usually has the .pb extension. The model can be trained and frozen by package DeePMD-kit, which can have either double or single float precision interface.
The model deviation evalulates the consistency of the force predictions from multiple models. By default, only the maximal, minimal and average model deviations are output. If the key atomic is set, then the model deviation of force prediction of each atom will be output. The unit follows LAMMPS units and the scale factor is not applied.
By default, the model deviation is output in absolute value. If the keyword relative is set, then the relative model deviation of the force will be output, including values output by the keyword atomic. The relative model deviation of the force on atom \(i\) is defined by
where \(D_{f_i}\) is the absolute model deviation of the force on atom \(i\), \(f_i\) is the norm of the force and \(l\) is provided as the parameter of the keyword relative. If the keyword relative_v is set, then the relative model deviation of the virial will be output instead of the absolute value, with the same definition of that of the force:
If the keyword fparam is set, the given frame parameter(s) will be fed to the model. If the keyword fparam_from_compute is set, the global parameter(s) from compute command (e.g., temperature from compute temp command) will be fed to the model as the frame parameter(s). If the keyword aparam_from_compute is set, the atomic parameter(s) from compute command (e.g., per-atom translational kinetic energy from compute ke/atom command) will be fed to the model as the atom parameter(s). If the keyword aparam is set, the given atomic parameter(s) will be fed to the model, where each atom is assumed to have the same atomic parameter(s). If the keyword ttm is set, electronic temperatures from fix ttm command will be fed to the model as the atomic parameters.
Only a single pair_coeff command is used with the deepmd style which specifies atom names. These are mapped to LAMMPS atom types (integers from 1 to Ntypes) by specifying Ntypes additional arguments after * * in the pair_coeff command. If atom names are not set in the pair_coeff command, the training parameter type_map will be used by default. If a mapping value is specified as NULL, the mapping is not performed. This can be used when a deepmd potential is used as part of the hybrid pair style. The NULL values are placeholders for atom types that will be used with other potentials. If the training parameter type_map is not set, atom names in the pair_coeff command cannot be set. In this case, atom type indexes in type.raw (integers from 0 to Ntypes-1) will map to LAMMPS atom types.
Spin is specified by keywords virtual_len and spin_norm. If the keyword virtual_len is set, the distance between virtual atom and its corresponding real atom for each type of magnetic atoms will be fed to the model as the spin parameters. If the keyword spin_norm is set, the magnitude of the magnetic moment for each type of magnetic atoms will be fed to the model as the spin parameters.
Restrictions
The
deepmdpair style is provided in the USER-DEEPMD package, which is compiled from the DeePMD-kit, visit the DeePMD-kit website for more information.
Compute tensorial properties
The DeePMD-kit package provides the compute deeptensor/atom for computing atomic tensorial properties.
compute ID group-ID deeptensor/atom model_file
ID: user-assigned name of the computation
group-ID: ID of the group of atoms to compute
deeptensor/atom: the style of this compute
model_file: the name of the binary model file.
At this time, the training parameter type_map will be mapped to LAMMPS atom types.
Examples
compute dipole all deeptensor/atom dipole.pb
The result of the compute can be dumped to trajectory file by
dump 1 all custom 100 water.dump id type c_dipole[1] c_dipole[2] c_dipole[3]
Restrictions
The
deeptensor/atomcompute is provided in the USER-DEEPMD package, which is compiled from the DeePMD-kit, visit the DeePMD-kit website for more information.For the issue of using a unit style for
compute deeptensor/atom, refer to the discussions in units of this page.
Long-range interaction
The reciprocal space part of the long-range interaction can be calculated by LAMMPS command kspace_style. To use it with DeePMD-kit, one writes
pair_style deepmd graph.pb
pair_coeff * *
kspace_style pppm 1.0e-5
kspace_modify gewald 0.45
Please notice that the DeePMD does nothing to the direct space part of the electrostatic interaction, because this part is assumed to be fitted in the DeePMD model (the direct space cut-off is thus the cut-off of the DeePMD model). The splitting parameter gewald is modified by the kspace_modify command.
Use of the centroid/stress/atom to get the full 3x3 “atomic-virial”
The DeePMD-kit also allows the computation of per-atom stress tensor defined as:
Where \(\mathbf{r}_n\) is the atomic position of nth atom, \(\mathbf{v}_n\) velocity of the atom and \(\frac{de_m}{d\mathbf{r}_n}\) the derivative of the atomic energy.
In LAMMPS one can get the per-atom stress using the command centroid/stress/atom:
compute ID group-ID centroid/stress/atom NULL virial
see LAMMPS doc page for more details on the meaning of the keywords.
Changed in version v2.2.3: v2.2.2 or previous versions passed per-atom stress (cvatom) with the per-atom pressure tensor, which is inconsistent with LAMMPS’s definition. LAMMPS defines per-atom stress as the negative of the per-atom pressure tensor. Such behavior is corrected in v2.2.3.
Examples
In order of computing the 9-component per-atom stress
compute stress all centroid/stress/atom NULL virial
Thus c_stress is an array with 9 components in the order xx,yy,zz,xy,xz,yz,yx,zx,zy.
If you use this feature please cite D. Tisi, L. Zhang, R. Bertossa, H. Wang, R. Car, S. Baroni - arXiv preprint arXiv:2108.10850, 2021
Computation of heat flux
Using a per-atom stress tensor one can, for example, compute the heat flux defined as:
to compute the heat flux with LAMMPS:
compute ke_ID all ke/atom
compute pe_ID all pe/atom
compute stress_ID group-ID centroid/stress/atom NULL virial
compute flux_ID all heat/flux ke_ID pe_ID stress_ID
Examples
compute ke all ke/atom
compute pe all pe/atom
compute stress all centroid/stress/atom NULL virial
compute flux all heat/flux ke pe stress
c_flux is a global vector of length 6. The first three components are the \(x\), \(y\) and \(z\) components of the full heat flux vector. The others are the components of the so-called convective portion, see LAMMPS doc page for more detailes.
If you use these features please cite D. Tisi, L. Zhang, R. Bertossa, H. Wang, R. Car, S. Baroni - arXiv preprint arXiv:2108.10850, 2021
Run path-integral MD with i-PI
The i-PI works in a client-server model. The i-PI provides the server for integrating the replica positions of atoms, while the DeePMD-kit provides a client named dp_ipi that computes the interactions (including energy, forces and virials). The server and client communicate via the Unix domain socket or the Internet socket. Installation instructions for i-PI can be found here. The client can be started by
i-pi input.xml &
dp_ipi water.json
It is noted that multiple instances of the client allow for computing, in parallel, the interactions of multiple replicas of the path-integral MD.
water.json is the parameter file for the client dp_ipi, and an example is provided:
{
"verbose": false,
"use_unix": true,
"port": 31415,
"host": "localhost",
"graph_file": "graph.pb",
"coord_file": "conf.xyz",
"atom_type": {
"OW": 0,
"HW1": 1,
"HW2": 1
}
}
The option use_unix is set to true to activate the Unix domain socket, otherwise, the Internet socket is used.
The option port should be the same as that in input.xml:
<port>31415</port>
The option graph_file provides the file name of the frozen model. The model can have either double or single float precision interface.
The dp_ipi gets the atom names from an XYZ file provided by coord_file (meanwhile ignores all coordinates in it) and translates the names to atom types by rules provided by atom_type.
Running MD with GROMACS
DP/MM Simulation
This part gives a simple tutorial on how to run a DP/MM simulation for methane in water, which means using DP for methane and TIP3P for water. All relevant files can be found in examples/methane.
Topology Preparation
Similar to QM/MM simulation, the internal interactions (including bond, angle, dihedrals, LJ, Columb) of the region described by a neural network potential (NNP) have to be turned off. In GROMACS, bonded interactions can be turned off by modifying [ bonds ], [ angles ], [ dihedrals ] and [ pairs ] sections. And LJ and Columb interactions must be turned off by [ exclusions ] section.
For example, if one wants to simulate ethane in water, using DeepPotential for methane and TIP3P for water, the topology of methane should be like the following (as presented in examples/methane/methane.itp):
[ atomtypes ]
;name btype mass charge ptype sigma epsilon
c3 c3 0.0 0.0 A 0.339771 0.451035
hc hc 0.0 0.0 A 0.260018 0.087027
[ moleculetype ]
;name nrexcl
methane 3
[ atoms ]
; nr type resnr residue atom cgnr charge mass
1 c3 1 MOL C1 1 -0.1068 12.010
2 hc 1 MOL H1 2 0.0267 1.008
3 hc 1 MOL H2 3 0.0267 1.008
4 hc 1 MOL H3 4 0.0267 1.008
5 hc 1 MOL H4 5 0.0267 1.008
[ bonds ]
; i j func b0 kb
1 2 5
1 3 5
1 4 5
1 5 5
[ exclusions ]
; ai aj1 aj2 aj3 aj4
1 2 3 4 5
2 1 3 4 5
3 1 2 4 5
4 1 2 3 5
5 1 2 3 4
For comparison, the original topology file generated by acpype will be:
; methane_GMX.itp created by acpype (v: 2021-02-05T22:15:50CET) on Wed Sep 8 01:21:53 2021
[ atomtypes ]
;name bond_type mass charge ptype sigma epsilon Amb
c3 c3 0.00000 0.00000 A 3.39771e-01 4.51035e-01 ; 1.91 0.1078
hc hc 0.00000 0.00000 A 2.60018e-01 8.70272e-02 ; 1.46 0.0208
[ moleculetype ]
;name nrexcl
methane 3
[ atoms ]
; nr type resi res atom cgnr charge mass ; qtot bond_type
1 c3 1 MOL C1 1 -0.106800 12.01000 ; qtot -0.107
2 hc 1 MOL H1 2 0.026700 1.00800 ; qtot -0.080
3 hc 1 MOL H2 3 0.026700 1.00800 ; qtot -0.053
4 hc 1 MOL H3 4 0.026700 1.00800 ; qtot -0.027
5 hc 1 MOL H4 5 0.026700 1.00800 ; qtot 0.000
[ bonds ]
; ai aj funct r k
1 2 1 1.0970e-01 3.1455e+05 ; C1 - H1
1 3 1 1.0970e-01 3.1455e+05 ; C1 - H2
1 4 1 1.0970e-01 3.1455e+05 ; C1 - H3
1 5 1 1.0970e-01 3.1455e+05 ; C1 - H4
[ angles ]
; ai aj ak funct theta cth
2 1 3 1 1.0758e+02 3.2635e+02 ; H1 - C1 - H2
2 1 4 1 1.0758e+02 3.2635e+02 ; H1 - C1 - H3
2 1 5 1 1.0758e+02 3.2635e+02 ; H1 - C1 - H4
3 1 4 1 1.0758e+02 3.2635e+02 ; H2 - C1 - H3
3 1 5 1 1.0758e+02 3.2635e+02 ; H2 - C1 - H4
4 1 5 1 1.0758e+02 3.2635e+02 ; H3 - C1 - H4
DeepMD Settings
Before running simulations, we need to tell GROMACS to use DeepPotential by setting the environment variable GMX_DEEPMD_INPUT_JSON:
export GMX_DEEPMD_INPUT_JSON=input.json
Then, in your working directories, we have to write input.json file:
{
"graph_file": "/path/to/graph.pb",
"type_file": "type.raw",
"index_file": "index.raw",
"lambda": 1.0,
"pbc": false
}
Here is an explanation for these settings:
graph_file: The graph file (with suffix .pb) generated bydp freezecommandtype_file: File to specify DP atom types (in space-separated format). Here,type.rawlooks like
1 0 0 0 0
index_file: File containing indices of DP atoms (in space-separated format), which should be consistent with the indices’ order in .gro file but starting from zero. Here,index.rawlooks like
0 1 2 3 4
lambda: Optional, default 1.0. Used in alchemical calculations.pbc: Optional, default true. If true, the GROMACS periodic condition is passed to DeepMD.
Run Simulation
Finally, you can run GROMACS using gmx mdrun as usual.
All-atom DP Simulation
This part gives an example of how to simulate all atoms described by a DeepPotential with Gromacs, taking water as an example. Instead of using [ exclusions ] to turn off the non-bonded energies, we can simply do this by setting LJ parameters (i.e. epsilon and sigma) and partial charges to 0, as shown in examples/water/gmx/water.top:
[ atomtypes ]
; name at.num mass charge ptype sigma epsilon
HW 1 1.008 0.0000 A 0.00000e+00 0.00000e+00
OW 8 16.00 0.0000 A 0.00000e+00 0.00000e+00
As mentioned in the above section, input.json and relevant files (index.raw, type.raw) should also be created. Then, we can start the simulation under the NVT ensemble and plot the radial distribution function (RDF) by gmx rdf command. We can see that the RDF given by Gromacs+DP matches perfectly with Lammps+DP, which further provides an evidence on the validity of our simulation. 
However, we still recommend you run an all-atom DP simulation using LAMMPS since it is more stable and efficient.
Interfaces out of DeePMD-kit
The codes of the following interfaces are not a part of the DeePMD-kit package and maintained by other repositories. We list these interfaces here for user convenience.
dpdata
dpdata provides the predict method for System class:
import dpdata
dsys = dpdata.LabeledSystem("OUTCAR")
dp_sys = dsys.predict("frozen_model_compressed.pb")
By inferring with the DP model frozen_model_compressed.pb, dpdata will generate a new labeled system dp_sys with inferred energies, forces, and virials.
OpenMM plugin for DeePMD-kit
An OpenMM plugin is provided from JingHuangLab/openmm_deepmd_plugin, written by the Huang Lab at Westlake University.
Amber interface to DeePMD-kit
Starting from AmberTools24, sander includes an interface to the DeePMD-kit, which implements the Deep Potential Range Corrected (DPRc) correction. The DPRc model and the interface were developed by the York Lab from Rutgers University. More details are available in
Amber Reference Manuals, providing documentation for how to enable the interface and the
&dprcnamelist;GitLab RutgersLBSR/AmberDPRc, providing examples mdin files;
DP-Amber, a tiny tool to convert Amber trajectory to DPRc training data;
CP2K interface to DeePMD-kit
CP2K v2024.2 adds an interface to the DeePMD-kit for molecular dynamics. Read the CP2K manual for details.
DP-GEN
DP-GEN provides a workflow to generate accurate DP models by calling DeePMD-kit’s command line interface (CLI) in the local or remote server. Details can be found in this paper.
MLatom
Mlatom provides an interface to the DeePMD-kit within MLatom’s workflow by calling DeePMD-kit’s CLI. Details can be found in this paper.
ABACUS
ABACUS can run molecular dynamics with a DP model. User is required to build ABACUS with DeePMD-kit.
Use NVNMD
Introduction
NVNMD stands for non-von Neumann molecular dynamics.
This is the training code we used to generate the results in our paper entitled “Accurate and Efficient Molecular Dynamics based on Machine Learning and non von Neumann Architecture”, which has been accepted by npj Computational Materials (DOI: 10.1038/s41524-022-00773-z).
Any user can follow two consecutive steps to run molecular dynamics (MD) on the proposed NVNMD computer, which has been released online: (i) to train a machine learning (ML) model that can decently reproduce the potential energy surface (PES); and (ii) to deploy the trained ML model on the proposed NVNMD computer, then run MD there to obtain the atomistic trajectories.
Training
Our training procedure consists of not only continuous neural network (CNN) training but also quantized neural network (QNN) training which uses the results of CNN as inputs. It is performed on CPU or GPU by using the training codes we open-sourced online.
To train an ML model that can decently reproduce the PES, a training and testing data set should be prepared first. This can be done by using either the state-of-the-art active learning tools or the outdated (i.e., less efficient) brute-force density functional theory (DFT)-based ab-initio molecular dynamics (AIMD) sampling.
If you just want to simply test the training function, you can use the example in the $deepmd_source_dir/examples/nvnmd directory. If you want to fully experience training and running MD functions, you can download the complete example from the website.
Then, copy the data set to the working directory
mkdir -p $workspace
cd $workspace
mkdir -p data
cp -r $dataset data
where $dataset is the path to the data set and $workspace is the path to the working directory.
Input script
Create and go to the training directory.
mkdir train
cd train
Then copy the input script train_cnn.json and train_qnn.json to the directory train
cp -r $deepmd_source_dir/examples/nvnmd/train/train_cnn.json train_cnn.json
cp -r $deepmd_source_dir/examples/nvnmd/train/train_qnn.json train_qnn.json
The structure of the input script is as follows
{
"nvnmd": {},
"learning_rate": {},
"loss": {},
"training": {}
}
nvnmd
The “nvnmd” section is defined as
{
"version": 0,
"max_nnei": 128,
"net_size": 128,
"sel": [60, 60],
"rcut": 6.0,
"rcut_smth": 0.5,
"type_map": ["Ge", "Te"]
}
where items are defined as:
Item | Mean | Optional Value |
|---|---|---|
version | the version of network structure | 0 or 1 |
max_nnei | the maximum number of neighbors that do not distinguish element types | 128 or 256 |
net_size | the size of nueral network | 128 |
sel | the number of neighbors | version 0: integer list of lengths 1 to 4 are acceptable; version 1: integer |
rcut | the cutoff radial | (0, 8.0] |
rcut_smth | the smooth cutoff parameter | (0, 8.0] |
type_map | mapping atom type to the name (str) of the type | string list, optional |
Multiple versions of the nvnmd model correspond to different network structures. nvnmd-v0 and nvnmd-v1 differ in the following ways:
nvnmd-v0andnvnmd-v1use these_adescriptor andse_attendescriptor, respectivelynvnmd-v0has 1 set of parameters for each element and supports up to 4 element types.nvnmd-v1shares 1 set of parameters for each element and supports up to 31 types.nvnmd-v0distinguishes between neighboring atoms, soselis a list of integers.nvnmd-v1does not distinguish between neighboring atoms, soselis an integer.
learning_rate
The “learning_rate” section is defined as
{
"type": "exp",
"start_lr": 1e-3,
"stop_lr": 3e-8,
"decay_steps": 5000
}
where items are defined as:
Item | Mean | Optional Value |
|---|---|---|
type | learning rate variant type | exp |
start_lr | the learning rate at the beginning of the training | a positive real number |
stop_lr | the desired learning rate at the end of the training | a positive real number |
decay_stops | the learning rate is decaying every {decay_stops} training steps | a positive integer |
loss
The “loss” section is defined as
{
"start_pref_e": 0.02,
"limit_pref_e": 2,
"start_pref_f": 1000,
"limit_pref_f": 1,
"start_pref_v": 0,
"limit_pref_v": 0
}
where items are defined as:
Item | Mean | Optional Value |
|---|---|---|
start_pref_e | the loss factor of energy at the beginning of the training | zero or positive real number |
limit_pref_e | the loss factor of energy at the end of the training | zero or positive real number |
start_pref_f | the loss factor of force at the beginning of the training | zero or positive real number |
limit_pref_f | the loss factor of force at the end of the training | zero or positive real number |
start_pref_v | the loss factor of virial at the beginning of the training | zero or positive real number |
limit_pref_v | the loss factor of virial at the end of the training | zero or positive real number |
training
The “training” section is defined as
{
"seed": 1,
"stop_batch": 1000000,
"numb_test": 1,
"disp_file": "lcurve.out",
"disp_freq": 1000,
"save_ckpt": "model.ckpt",
"save_freq": 10000,
"training_data": {
"systems": ["system1_path", "system2_path", "..."],
"set_prefix": "set",
"batch_size": ["batch_size_of_system1", "batch_size_of_system2", "..."]
}
}
where items are defined as:
Item | Mean | Optional Value |
|---|---|---|
seed | the randome seed | a integer |
stop_batch | the total training steps | a positive integer |
numb_test | the accuracy is test by using {numb_test} sample | a positive integer |
disp_file | the log file where the training message display | a string |
disp_freq | display frequency | a positive integer |
save_ckpt | path prefix of check point files | a string |
save_freq | save frequency | a positive integer |
systems | a list of data directory which contains the dataset | string list |
set_prefix | the prefix of dataset | a string |
batch_size | a list of batch size of corresponding dataset | a integer list |
Training
Training can be invoked by
# step1: train CNN
dp train-nvnmd train_cnn.json -s s1
# step2: train QNN
dp train-nvnmd train_qnn.json -s s2
After the training process, you will get two folders: nvnmd_cnn and nvnmd_qnn. The nvnmd_cnn contains the model after continuous neural network (CNN) training. The nvnmd_qnn contains the model after quantized neural network (QNN) training. The binary file nvnmd_qnn/model.pb is the model file that is used to perform NVNMD in the server [http://nvnmd.picp.vip].
You can also restart the CNN training from the path prefix of checkpoint files (nvnmd_cnn/model.ckpt) by
dp train-nvnmd train_cnn.json -r nvnmd_cnn/model.ckpt -s s1
You can also initialize the CNN model and train it by
mv nvnmd_cnn nvnmd_cnn_bck
cp train_cnn.json train_cnn2.json
# please edit train_cnn2.json
dp train-nvnmd train_cnn2.json -s s1 -i nvnmd_cnn_bck/model.ckpt
Testing
The frozen model can be used in many ways. The most straightforward testing can be invoked by
mkdir test
dp test -m ./nvnmd_qnn/frozen_model.pb -s path/to/system -d ./test/detail -n 99999 -l test/output.log
where the frozen model file to import is given via the -m command line flag, the path to the testing data set is given via the -s command line flag, and the file containing details of energy, forces and virials accuracy is given via the -d command line flag, the amount of data for testing is given via the -n command line flag.
Running MD in Bohrium
After CNN and QNN training, you can upload the ML model to our online NVNMD system and run MD there through Bohrium (https://bohrium.dp.tech). Bohrium is a research platfrom designed for AI for Science Era. For more information, please refer to Bohrium Introduction.
Registration
Click here to register a Bohrium account. If you already have an account for other DP products, you can skip this step and log in directly.
Top-up and create a project
After entering the homepage, you can click on the User Center in the lower left corner to top-up by yourself.

After completing the top-up, click on the Projects, and then click New Project in the upper right corner of the page. Give the project a name that is easy for you to recognize and click OK. If the project has other collaborators, you can refer to Project Collaboration for more information.

Run job
We will use Utility to submit jobs, you can install it with the following command
pip install lbg
When using the Lebesgue Utility for the first time, you need to configure your account by
lbg config account
Enter your Bohrium account and the corresponding password.
Then you need prepare the configuration file job.json, the configuration file is as follows
{
"job_name": "test",
"command": "/usr/bin/lmp_mpi < in.lmp;",
"log_file": "OUTCAR",
"machine_type": "c4_m16_cpu",
"job_type": "container",
"image_name": "lammps_dp:29Sep2021",
"platform": "hnugba",
"region": "default",
"project_id": 0000
}
where items are defined as:
Item | Mean | Optional Value |
|---|---|---|
job_name | the name of computing job, which can be named freely | a string |
command | the command to be executed on the computing node | a string |
log_file | the log file that can be viewed at any time during the calculation process, which can be viewed on the Bohrium “Jobs” page | a string |
machine_type | the machine type used for the job | “c1_m4_cpu”, “c4_m16_cpu”, “c8_m32_cpu” |
job_type | the job type | “container” |
image_name | the image name used for the job | “lammps_dp:29Sep2021” |
platform | resource provider | “hnugba” |
project_id | the project ID to which the job belongs, which can be viewed on the “Projects” page | a integer |
Notice:The task will use 4 CPU cores for computation, so do not repeatedly use the mpirun command, otherwise an error will be reported. All 0000 after “project_id” need to be replaced with your own project ID, which can be viewed on the “Projects” page. Also, the JSON file format requires that no commas be added after the last field within the {}, otherwise, there will be a syntax error. Please check the documentation for the latest hardware configuration information.
In addition, it is necessary to prepare input script of the MD simulation, the ML model named model.pb obtained by QNN training and data files containing information required for running an MD simulation (e.g., coord.lmp containing initial atom coordinates).
In the input script, one needs to specify the pair style as follows
pair_style nvnmd model.pb
pair_coeff * *
where model.pb is the path to model.
After preparing the configuration file and the required files for calculation, using Lebesgue Utility to submit the job
lbg job submit -i job.json -p ./
where the configuration file for the job is given via the -i command line flag, the directory where the input files are located is given via the -p command line flag. Bohrium will package and upload the specified directory, and after decompressing it on the computing node, it will switch the working directory to that directory.
After the job is submitted successfully, the JOB ID and JOB GROUP ID will be output.

Check job status
After successfully submitting the job, you can view the progress and related logs of the submitted jobs on the Jobs page.

Terminate and delete jobs
You can choose between terminate and delete operations.
Terminate: To end running jobs/job groups in advance, save the generated result files, and the status of the terminated jobs will be changed to “completed”.
Delete: To end running jobs/job groups, the status of the jobs will be changed to “failed”. Job result files will be deleted, and the jobs/job groups disappear from the list. The delete operation cannot be undone.
The Jobs page provides buttons to end jobs and job groups


You can also use the Lebesgue Utility tool to end jobs
lbg jobgroup terminate <JOB GROUP ID>
lbg job terminate <JOB ID>
lbg jobgroup rm <JOB GROUP ID>
lbg job rm <JOB ID>
Download Results
After the calculation is completed, you can download the results on the Jobs page, or save them to the data disk.

You can also download it using the commands of Lebesgue Utility
lbg job download <JOB ID>
or
lbg jobgroup download <JOB GROUP ID>
Running MD in Nvnmd website
After CNN and QNN training, you can upload the ML model to our online NVNMD system and run MD there.
Account application
The server website of NVNMD is available at http://nvnmd.picp.vip. You can visit the URL and enter the login interface.

To obtain an account, please send your application to the email (jie_liu@hnu.edu.cn, liujie@uw.edu). The username and password will be sent to you by email.
Adding task
After successfully obtaining the account, enter the username and password in the login interface, and click “Login” to enter the homepage.

The homepage displays the remaining calculation time and all calculation records not deleted. Click Add a new task to enter the interface for adding a new task.

Task name: name of the task
Upload mode: two modes of uploading results to online data storage, including
Manual uploadandAutomatic upload. Results need to be uploaded manually to online data storage withManual uploadmode and will be uploaded automatically withAutomatic uploadmode.Input script: input file of the MD simulation.
In the input script, one needs to specify the pair style as follows
pair_style nvnmd model.pb
pair_coeff * *
Model file: the ML model named
model.pbobtained by QNN training.Data files: data files containing the information required for running an MD simulation (e.g.,
coord.lmpcontaining initial atom coordinates).
Next, you can click Submit to submit the task and then automatically return to the homepage.

Then, click Refresh to view the latest status of all calculation tasks.
Cancelling calculation
For the task whose calculation status is Pending and Running, you can click the corresponding Cancel on the homepage to stop the calculation.

Downloading results
For the task whose calculation status is Completed, Failed and Cancelled, you can click the corresponding Package or Separate files in the Download results bar on the homepage to download results.
Click Package to download a zipped package of all files including input files and output results.

Click Separate files to download the required separate files.

If Manual upload mode is selected or the file has expired, click Upload on the download interface to upload manually.
Deleting record
For the task no longer needed, you can click the corresponding Delete on the homepage to delete the record.
Records cannot be retrieved after deletion.
Clearing records
Click Clear calculation records on the homepage to clear all records.
Records cannot be retrieved after clearing.
FAQs
As a consequence of differences in computers or systems, problems may occur. Some common circumstances are listed as follows. In addition, some frequently asked questions are listed as follows. If other unexpected problems occur, you’re welcome to contact us for help.
How to tune Fitting/embedding-net size ?
Here are some test forms on fitting-net size tuning or embedding-net size tuning performed on several different systems.
Al2O3
Fitting net size tuning form on Al2O3: (embedding-net size: [25,50,100])
Fitting-net size | Energy L2err(eV) | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|---|
[240,240,240] | 1.742252e-02 | 7.259383e-05 | 4.014115e-02 |
[80,80,80] | 1.799349e-02 | 7.497287e-05 | 4.042977e-02 |
[40,40,40] | 1.799036e-02 | 7.495984e-05 | 4.068806e-02 |
[20,20,20] | 1.834032e-02 | 7.641801e-05 | 4.094784e-02 |
[10,10,10] | 1.913058e-02 | 7.971073e-05 | 4.154775e-02 |
[5,5,5] | 1.932914e-02 | 8.053808e-05 | 4.188052e-02 |
[4,4,4] | 1.944832e-02 | 8.103467e-05 | 4.217826e-02 |
[3,3,3] | 2.068631e-02 | 8.619296e-05 | 4.300497e-02 |
[2,2,2] | 2.267962e-02 | 9.449840e-05 | 4.413609e-02 |
[1,1,1] | 2.813596e-02 | 1.172332e-04 | 4.781115e-02 |
[] | 3.135002e-02 | 1.306251e-04 | 5.373120e-02 |
[] means no hidden layer, but there is still a linear output layer. This situation is equal to the linear regression.
Embedding net size tuning form on Al2O3: (Fitting-net size: [240,240,240])
Embedding-net size | Energy L2err(eV) | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|---|
[25,50,100] | 1.742252e-02 | 7.259383e-05 | 4.014115e-02 |
[10,20,40] | 2.909990e-02 | 1.212496e-04 | 4.734667e-02 |
[5,10,20] | 3.357767e-02 | 1.399070e-04 | 5.706385e-02 |
[4,8,16] | 6.060367e-02 | 2.525153e-04 | 7.333304e-02 |
[3,6,12] | 5.656043e-02 | 2.356685e-04 | 7.793539e-02 |
[2,4,8] | 5.277023e-02 | 2.198759e-04 | 7.459995e-02 |
[1,2,4] | 1.302282e-01 | 5.426174e-04 | 9.672238e-02 |
Cu
Fitting net size tuning form on Cu: (embedding-net size: [25,50,100])
Fitting-net size | Energy L2err(eV) | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|---|
[240,240,240] | 4.135548e-02 | 1.615449e-04 | 8.940946e-02 |
[20,20,20] | 4.323858e-02 | 1.689007e-04 | 8.955762e-02 |
[10,10,10] | 4.399364e-02 | 1.718502e-04 | 8.962891e-02 |
[5,5,5] | 4.468404e-02 | 1.745470e-04 | 8.970111e-02 |
[4,4,4] | 4.463580e-02 | 1.743586e-04 | 8.972011e-02 |
[3,3,3] | 4.493758e-02 | 1.755374e-04 | 8.971303e-02 |
[2,2,2] | 4.500736e-02 | 1.758100e-04 | 8.973878e-02 |
[1,1,1] | 4.542073e-02 | 1.774247e-04 | 8.964761e-02 |
[] | 4.545168e-02 | 1.775456e-04 | 8.983201e-02 |
Embedding net size tuning form on Cu: (Fitting-net size: [240,240,240])
Embedding-net size | Energy L2err(eV) | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|---|
[25,50,100] | 4.135548e-02 | 1.615449e-04 | 8.940946e-02 |
[20,40,80] | 4.203562e-02 | 1.642016e-04 | 8.925881e-02 |
[15,30,60] | 4.146672e-02 | 1.619794e-04 | 8.936911e-02 |
[10,20,40] | 4.263060e-02 | 1.665258e-04 | 8.955818e-02 |
[5,10,20] | 4.994913e-02 | 1.951138e-04 | 9.007786e-02 |
[4,8,16] | 1.022157e-01 | 3.992802e-04 | 9.532119e-02 |
[3,6,12] | 1.362098e-01 | 5.320695e-04 | 1.073860e-01 |
[2,4,8] | 7.061800e-02 | 2.758515e-04 | 9.126418e-02 |
[1,2,4] && seed = 1 | 9.843161e-02 | 3.844985e-04 | 9.348505e-02 |
[1,2,4] && seed = 2 | 9.404335e-02 | 3.673568e-04 | 9.304089e-02 |
[1,2,4] && seed = 3 | 1.508016e-01 | 5.890688e-04 | 1.382356e-01 |
[1,2,4] && seed = 4 | 9.686949e-02 | 3.783965e-04 | 9.294820e-02 |
Water
Fitting net size tuning form on water: (embedding-net size: [25,50,100])
Fitting-net size | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|
[240,240,240] | 9.1589E-04 | 5.1540E-02 |
[200,200,200] | 9.3221E-04 | 5.2366E-02 |
[160,160,160] | 9.4274E-04 | 5.3403E-02 |
[120,120,120] | 9.5407E-04 | 5.3093E-02 |
[80,80,80] | 9.4605E-04 | 5.3402E-02 |
[40,40,40] | 9.8533E-04 | 5.5790E-02 |
[20,20,20] | 1.0057E-03 | 5.8232E-02 |
[10,10,10] | 1.0466E-03 | 6.2279E-02 |
[5,5,5] | 1.1154E-03 | 6.7994E-02 |
[4,4,4] | 1.1289E-03 | 6.9613E-02 |
[3,3,3] | 1.2368E-03 | 7.9786E-02 |
[2,2,2] | 1.3558E-03 | 9.7042E-02 |
[1,1,1] | 1.4633E-03 | 1.1265E-01 |
[] | 1.5193E-03 | 1.2136E-01 |
Embedding net size tuning form on water: (Fitting-net size: [240,240,240])
Embedding-net size | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|
[25,50,100] | 9.1589E-04 | 5.1540E-02 |
[20,40,80] | 9.5080E-04 | 5.3593E-02 |
[15,30,60] | 9.7996E-04 | 5.6338E-02 |
[10,20,40] | 1.0353E-03 | 6.2776E-02 |
[5,10,20] | 1.1254E-03 | 7.3195E-02 |
[4,8,16] | 1.2495E-03 | 8.0371E-02 |
[3,6,12] | 1.3604E-03 | 9.9883E-02 |
[2,4,8] | 1.4358E-03 | 9.7389E-02 |
[1,2,4] | 2.1765E-03 | 1.7276E-01 |
Mg-Al
Fitting net size tuning form on Mg-Al: (embedding-net size: [25,50,100])
Fitting-net size | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|
[240,240,240] | 3.9606e-03 | 1.6289e-02 |
[200,200,200] | 3.9449e-03 | 1.6471e-02 |
[160,160,160] | 4.0947e-03 | 1.6413e-02 |
[120,120,120] | 3.9234e-03 | 1.6283e-02 |
[80,80,80] | 3.9758e-03 | 1.6506e-02 |
[40,40,40] | 3.9142e-03 | 1.6348e-02 |
[20,20,20] | 4.1302e-03 | 1.7006e-02 |
[10,10,10] | 4.3433e-03 | 1.7524e-02 |
[5,5,5] | 5.3154e-03 | 1.9716e-02 |
[4,4,4] | 5.4210e-03 | 1.9710e-02 |
[2,2,2] | 6.2667e-03 | 2.2568e-02 |
[1,1,1] | 7.3676e-03 | 2.6375e-02 |
[] | 7.3999e-03 | 2.6097e-02 |
Embedding net size tuning form on Mg-Al: (Fitting-net size: [240,240,240])
Embedding-net size | Energy L2err/Natoms(eV) | Force L2err(eV/Angstrom) |
|---|---|---|
[25,50,100] | 3.9606e-03 | 1.6289e-02 |
[20,40,80] | 4.0292e-03 | 1.6555e-02 |
[15,30,60] | 4.1743e-03 | 1.7026e-02 |
[10,20,40] | 4.8138e-03 | 1.8516e-02 |
[5,10,20] | 5.6052e-03 | 2.0709e-02 |
[4,8,16] | 6.1335e-03 | 2.1450e-02 |
[3,6,12] | 6.6469e-03 | 2.3003e-02 |
[2,4,8] | 6.8222e-03 | 2.6318e-02 |
[1,2,4] | 1.0678e-02 | 3.9559e-02 |
How to control the parallelism of a job?
DeePMD-kit has three levels of parallelism. To get the best performance, one should control the number of threads used by DeePMD-kit. One should make sure the product of the parallel numbers is less than or equal to the number of cores available.
MPI (optional)
Parallelism for MPI is optional and used for multiple nodes, multiple GPU cards, or sometimes multiple CPU cores.
To enable MPI support for training, one should install horovod in advance. Note that the parallelism mode is data parallelism, so it is not expected to see the training time per batch decreases.
MPI support for inference is not directly supported by DeePMD-kit, but indirectly supported by the third-party software. For example, LAMMPS enables running simulations in parallel using the MPI parallel communication standard with distributed data. That software has to build against MPI.
Set the number of processes with:
mpirun -np $num_nodes dp
Note that mpirun here should be the same as the MPI used to build software. For example, one can use mpirun --version and lmp -h to see if mpirun and LAMMPS has the same MPI version.
Sometimes, $num_nodes and the nodes information can be directly given by the HPC scheduler system, if the MPI used here is the same as the MPI used to build the scheduler system. Otherwise, one have to manually assign these information.
Parallelism between independent operators
For CPU devices, TensorFlow use multiple streams to run independent operators (OP).
export TF_INTER_OP_PARALLELISM_THREADS=3
However, for GPU devices, TensorFlow uses only one compute stream and multiple copy streams. Note that some of DeePMD-kit OPs do not have GPU support, so it is still encouraged to set environmental variables even if one has a GPU.
Parallelism within an individual operators
For CPU devices, TF_INTRA_OP_PARALLELISM_THREADS controls parallelism within TensorFlow native OPs when TensorFlow is built against Eigen.
export TF_INTRA_OP_PARALLELISM_THREADS=2
OMP_NUM_THREADS is threads for OpenMP parallelism. It controls parallelism within TensorFlow native OPs when TensorFlow is built by Intel OneDNN and DeePMD-kit custom CPU OPs. It may also control parallelsim for NumPy when NumPy is built against OpenMP, so one who uses GPUs for training should also care this environmental variable.
export OMP_NUM_THREADS=2
There are several other environmental variables for OpenMP, such as KMP_BLOCKTIME. See Intel documentation for detailed information.
Tune the performance
There is no one general parallel configuration that works for all situations, so you are encouraged to tune parallel configurations yourself after empirical testing.
Here are some empirical examples. If you wish to use 3 cores of 2 CPUs on one node, you may set the environmental variables and run DeePMD-kit as follows:
export OMP_NUM_THREADS=3
export TF_INTRA_OP_PARALLELISM_THREADS=3
export TF_INTER_OP_PARALLELISM_THREADS=2
dp train input.json
For a node with 128 cores, it is recommended to start with the following variables:
export OMP_NUM_THREADS=16
export TF_INTRA_OP_PARALLELISM_THREADS=16
export TF_INTER_OP_PARALLELISM_THREADS=8
Again, in general, one should make sure the product of the parallel numbers is less than or equal to the number of cores available. In the above case, \(16 \times 8 = 128\), so threads will not compete with each other.
Do we need to set rcut < half boxsize?
When seeking the neighbors of atom i under periodic boundary conditions, DeePMD-kit considers all j atoms within cutoff rcut from atom i in all mirror cells.
So, there is no limitation on the setting of rcut.
PS: The reason why some software requires rcut < half box size is that they only consider the nearest mirrors from the center cell. DeePMD-kit is different from them.
How to set sel?
sel is short for “selected number of atoms in rcut”.
sel_a[i] is a list of integers. The length of the list should be the same as the number of atom types in the system.
sel_a[i] gives the number of the selected number of type i neighbors within rcut. To ensure that the results are strictly accurate, sel_a[i] should be larger than the largest number of type i neighbors in the rcut.
However, the computation overhead increases with sel_a[i], therefore, sel_a[i] should be as small as possible.
The setting of sel_a[i] should balance the above two considerations.
Installation
Inadequate versions of gcc/g++
Sometimes you may use a gcc/g++ of version < 4.8. In this way, you can still compile all the parts of TensorFlow and most of the parts of DeePMD-kit, but i-Pi and GROMACS plugins will be disabled automatically. Or if you have a gcc/g++ of version > 4.8, say, 7.2.0, you may choose to use it by doing
export CC=/path/to/gcc-7.2.0/bin/gcc
export CXX=/path/to/gcc-7.2.0/bin/g++
Build files left in DeePMD-kit
When you try to build a second time when installing DeePMD-kit, files produced before may contribute to failure. Thus, you may clear them by
cd build
rm -r *
and redo the cmake process.
The temperature undulates violently during the early stages of MD
This is probably because your structure is too far from the equilibrium configuration.
To make sure the potential model is truly accurate, we recommend checking model deviation.
MD: cannot run LAMMPS after installing a new version of DeePMD-kit
This typically happens when you install a new version of DeePMD-kit and copy directly the generated USER-DEEPMD to a LAMMPS source code folder and re-install LAMMPS.
To solve this problem, it suffices to first remove USER-DEEPMD from the LAMMPS source code by
make no-user-deepmd
and then install the new USER-DEEPMD.
If this does not solve your problem, try to decompress the LAMMPS source tarball and install LAMMPS from scratch again, which typically should be very fast.
Model compatibility
When the version of DeePMD-kit used to train the model is different from the that of DeePMD-kit running MDs, one has the problem of model compatibility.
DeePMD-kit guarantees that the codes with the same major and minor revisions are compatible. That is to say, v0.12.5 is compatible with v0.12.0, but is not compatible with v0.11.0 or v1.0.0.
One can execute dp convert-from to convert an old model to a new one.
Model version | v0.12 | v1.0 | v1.1 | v1.2 | v1.3 | v2.0 | v2.1 | v2.2 |
|---|---|---|---|---|---|---|---|---|
Compatibility | 😊 | 😊 | 😊 | 😊 | 😊 | 😄 | 😄 | 😄 |
Legend:
😄: The model is compatible with the DeePMD-kit package.
😊: The model is incompatible with the DeePMD-kit package, but one can execute
dp convert-fromto convert an old model to v2.2.😢: The model is incompatible with the DeePMD-kit package, and there is no way to convert models.
Why does a model have low precision?
Many phenomena are caused by model accuracy. For example, during simulations, temperatures explode, structures fall apart, and atoms are lost. One can test the model to confirm whether the model has the enough accuracy.
There are many reasons for a low-quality model. Some common reasons are listed below.
Data
Data units and signs
The unit of training data should follow what is listed in data section. Usually, the package to calculate the training data has different units from those of the DeePMD-kit. It is noted that some software label the energy gradient as forces, instead of the negative energy gradient. It is neccessary to check them carefully to avoid inconsistent data.
SCF coverage and data accuracy
The accuracy of models will not exceed the accuracy of training data, so the training data should reach enough accuracy. Here is a checklist for the accuracy of data:
SCF should converge to a suitable threshold for all points in the training data.
The convergence of the energy, force and virial with respect to the energy cutoff and k-spacing sample is checked.
Sometimes, QM software may generate unstable outliers, which should be removed.
The data should be extracted with enough digits and stored with the proper precision. Large energies may have low precision when they are stored as the single-precision floating-point format (FP32).
Enough data
If the model performs good on the training data, but has bad accuracy on another data, this means some data space is not covered by the training data. It can be validated by evaluting the model deviation with multiple models. If the model deviation of these data is high for some data, try to collect more data using DP-GEN.
Values of data
One should be aware that the errors of some data is also affected by the absolute values of this data. Stable structures tend to be more precise than unstable structures because unstable structures may have larger forces. Also, errors will be introduced in the Projector augmented wave (PAW) DFT calculations when the atoms are very close due to the overlap of pseudo-potentials. It is expected to see that data with large forces has larger errors and it is better to compare different models only with the same data.
Model
Enough sel
The sel of the descriptors must be enough for both training and test data. Otherwise, the model will be unreliable and give wrong results.
Cutoff radius
The model cannot fit the long-term interaction out of the cutoff radius. This is a designed approximation for performance, but one has to choose proper cutoff radius for the system.
Neural network size
The size of neural networks will affect the accuracy, but if one follows the parameters in the examples, this effect is insignificant. See FAQ: How to tune Fitting/embedding-net size for details.
Neural network precision
In some cases, one may want to use the FP32 precision to make the model faster. For some applications, FP32 is enough and thus is recommended, but one should still be aware that the precision of FP32 is not as high as that of FP64.
Training
Training steps
Generally speaking, the longer the number of training steps, the better the model. A balance between model accuracy and training time can be achieved. If one finds that model accuracy decreases with training time, there may be a problem with the data. See the data section for details.
Learning rate
Both too large and too small learning rate may affect the training. It is recommended to start with a large learning rate and end with a small learning rate. The learning rate from the examples is a good choice to start.
Find DeePMD-kit C/C++ library from CMake
After DeePMD-kit C/C++ library is installed, one can find DeePMD-kit from CMake:
find_package(DeePMD REQUIRED)
Note that you may need to add ${deepmd_root} to the cached CMake variable CMAKE_PREFIX_PATH.
To link against the C interface library, using
target_link_libraries(some_library PRIVATE DeePMD::deepmd_c)
To link against the C++ interface library, using
target_link_libraries(some_library PRIVATE DeePMD::deepmd_cc)
Create a model
If you’d like to create a new model that isn’t covered by the existing DeePMD-kit library, but reuse DeePMD-kit’s other efficient modules such as data processing, trainner, etc, you may want to read this section.
To incorporate your custom model you’ll need to:
Register and implement new components (e.g. descriptor) in a Python file. You may also want to register new TensorFlow OPs if necessary.
Register new arguments for user inputs.
Package new codes into a Python package.
Test new models.
Design a new component
When creating a new component, take descriptor as the example, you should inherit deepmd.descriptor.descriptor.Descriptor class and override several methods. Abstract methods such as deepmd.descriptor.descriptor.Descriptor.build must be implemented and others are not. You should keep arguments of these methods unchanged.
After implementation, you need to register the component with a key:
from deepmd.descriptor import Descriptor
@Descriptor.register("some_descrpt")
class SomeDescript(Descriptor):
def __init__(self, arg1: bool, arg2: float) -> None:
pass
Register new arguments
To let someone uses your new component in their input file, you need to create a new method that returns some Argument of your new component, and then register new arguments. For example, the code below
from typing import List
from dargs import Argument
from deepmd.utils.argcheck import descrpt_args_plugin
@descrpt_args_plugin.register("some_descrpt")
def descrpt_some_args() -> List[Argument]:
return [
Argument("arg1", bool, optional=False, doc="balabala"),
Argument("arg2", float, optional=True, default=6.0, doc="haha"),
]
allows one to use your new descriptor as below:
"descriptor" :{
"type": "some_descrpt",
"arg1": true,
"arg2": 6.0
}
The arguments here should be consistent with the class arguments of your new component.
Package new codes
You may use setuptools to package new codes into a new Python package. It’s crucial to add your new component to entry_points['deepmd'] in setup.py:
entry_points = (
{
"deepmd": [
"some_descrpt=deepmd_some_descrtpt:SomeDescript",
],
},
)
where deepmd_some_descrtpt is the module of your codes. It is equivalent to from deepmd_some_descrtpt import SomeDescript.
If you place SomeDescript and descrpt_some_args into different modules, you are also expected to add descrpt_some_args to entry_points.
After you install your new package, you can now use dp train to run your new model.
Atom Type Embedding
Overview
Here is an overview of the DeePMD-kit algorithm. Given a specific centric atom, we can obtain the matrix describing its local environment, named \(\mathcal R\). It consists of the distance between the centric atom and its neighbors, as well as a direction vector. We can embed each distance into a vector of \(M_1\) dimension by an embedding net, so the environment matrix \(\mathcal R\) can be embedded into matrix \(\mathcal G\). We can thus extract a descriptor vector (of \(M_1 \times M_2\) dim) of the centric atom from the \(\mathcal G\) by some matrix multiplication, and put the descriptor into fitting net to get the predicted energy \(E\). The vanilla version of DeePMD-kit builds embedding net and fitting net relying on the atom type, resulting in \(O(N)\) memory usage. After applying atom type embedding, in DeePMD-kit v2.0, we can share one embedding net and one fitting net in total, which reduces training complexity largely.
Preliminary
In the following chart, you can find the meaning of symbols used to clarify the atom-type embedding algorithm.
\(i\): Type of centric atom
\(j\): Type of neighbor atom
\(s_{ij}\): Distance between centric atom and neighbor atom
\(\mathcal G_{ij}(\cdot)\): Origin embedding net, take \(s_{ij}\) as input and output embedding vector of \(M_1\) dim
\(\mathcal G(\cdot)\): Shared embedding net
\(\text{Multi}(\cdot)\): Matrix multiplication and flattening, output the descriptor vector of \(M_1\times M_2\) dim
\(F_i(\cdot)\): Origin fitting net, take the descriptor vector as input and output energy
\(F(\cdot)\): Shared fitting net
\(A(\cdot)\): Atom type embedding net, input is atom type, the output is type embedding vector of dim nchanl
So, we can formulate the training process as follows. Vanilla DeePMD-kit algorithm:
DeePMD-kit applying atom type embedding:
or
The difference between the two variants above is whether using the information of centric atom when generating the descriptor. Users can choose by modifying the type_one_side hyper-parameter in the input JSON file.
How to use
A detailed introduction can be found at se_e2_a_tebd. Looking for a fast start-up, you can simply add a type_embedding section in the input JSON file as displayed in the following, and the algorithm will adopt the atom type embedding algorithm automatically. An example of type_embedding is like
"type_embedding":{
"neuron": [2, 4, 8],
"resnet_dt": false,
"seed": 1
}
Code Modification
Atom-type embedding can be applied to varied embedding net and fitting net, as a result, we build a class TypeEmbedNet to support this free combination. In the following, we will go through the execution process of the code to explain our code modification.
trainer (train/trainer.py)
In trainer.py, it will parse the parameter from the input JSON file. If a type_embedding section is detected, it will build a TypeEmbedNet, which will be later input in the model. model will be built in the function _build_network.
model (model/ener.py)
When building the operation graph of the model in model.build. If a TypeEmbedNet is detected, it will build the operation graph of type embed net, embedding net and fitting net by order. The building process of type embed net can be found in TypeEmbedNet.build, which output the type embedding vector of each atom type (of [\(\text{ntypes} \times \text{nchanl}\)] dimensions). We then save the type embedding vector into input_dict, so that they can be fetched later in embedding net and fitting net.
embedding net (descriptor/se*.py)
In embedding net, we shall take local environment \(\mathcal R\) as input and output matrix \(\mathcal G\). Functions called in this process by the order is
build -> _pass_filter -> _filter -> _filter_lower
_pass_filter: It will first detect whether an atom type embedding exists, if so, it will apply atom type embedding algorithm and doesn’t divide the input by type.
_filter: It will call _filter_lower function to obtain the result of matrix multiplication (\(\mathcal G^T\cdot \mathcal R\)), do further multiplication involved in \(\text{Multi}(\cdot)\), and finally output the result of descriptor vector of \(M_1 \times M_2\) dim.
_filter_lower: The main function handling input modification. If type embedding exists, it will call _concat_type_embedding function to concat the first column of input \(\mathcal R\) (the column of \(s_{ij}\)) with the atom type embedding information. It will decide whether to use the atom type embedding vector of the centric atom according to the value of type_one_side (if set True, then we only use the vector of the neighbor atom). The modified input will be put into the fitting net to get \(\mathcal G\) for further matrix multiplication stage.
fitting net (fit/ener.py)
In fitting net, it takes the descriptor vector as input, whose dimension is [natoms, \(M_1\times M_2\)]. Because we need to involve information on the centric atom in this step, we need to generate a matrix named atype_embed (of dim [natoms, nchanl]), in which each row is the type embedding vector of the specific centric atom. The input is sorted by type of centric atom, we also know the number of a particular atom type (stored in natoms[2+i]), thus we get the type vector of the centric atom. In the build phase of the fitting net, it will check whether type embedding exists in input_dict and fetch them. After that, call embed_atom_type function to look up the embedding vector for the type vector of the centric atom to obtain atype_embed, and concat input with it ([input, atype_embed]). The modified input goes through fitting net` to get predicted energy.
Note
You can’t apply the compression method while using atom-type embedding.
Coding Conventions
Preface
The aim of these coding standards is to help create a codebase with a defined and consistent coding style that every contributor can get easily familiar with. This will in enhance code readability as there will be no different coding styles from different contributors and everything will be documented. Also, PR diffs will be smaller because of the unified coding style. Finally, static typing will help in hunting down potential bugs before the code is even run.
Contributed code will not be refused merely because it does not strictly adhere to these conditions; as long as it’s internally consistent, clean, and correct, it probably will be accepted. But don’t be surprised if the “offending” code gets fiddled with overtime to conform to these conventions.
There are also pre-commit CI checks for python code style which will automatically fix the PR.
Python
Rules
The code must be compatible with the oldest supported version of python which is 3.7
The project follows the generic coding conventions as specified in the Style Guide for Python Code, Docstring Conventions and Typing Conventions PEPs, clarified and extended as follows:
Do not use “
*” imports such asfrom module import *. Instead, list imports explicitly.Use 4 spaces per indentation level. No tabs.
No one-liner compound statements (i.e., no
if x: return: use two lines).Maximum line length is 88 characters as recommended by black which is less strict than Docstring Conventions suggests.
Use “StudlyCaps” for class names.
Use “lowercase” or “lowercase_with_underscores” for function, method, variable names and module names. For short names, joined lowercase may be used (e.g. “tagname”). Choose what is most readable.
No single-character variable names, except indices in loops that encompass a very small number of lines (
for i in range(5): ...).Avoid lambda expressions. Use named functions instead.
Avoid functional constructs (filter, map, etc.). Use list comprehensions instead.
Use
"double quotes"for string literals, and"""triple double quotes"""for docstring’s. Single quotes are OK for something likef"something {'this' if x else 'that'}"
Use f-strings
s = f"{x:.2f}"instead of old style formating with"%f" % x. string format method"{x:.2f}".format()may be used sparsely where it is more convenient than f-strings.
Whitespace
Python is not C/C++ so whitespace should be used sparingly to maintain code readability
Read the Whitespace in Expressions and Statements section of PEP8.
Avoid trailing whitespaces.
Do not use excessive whitespace in your expressions and statements.
You should have blank spaces after commas, colons, and semi-colons if it isn’t trailing next to the end of a bracket, brace, or parentheses.
With any operators you should use space on both sides of the operator.
Colons for slicing are considered a binary operator, and should not have any spaces between them.
You should have parentheses with no space, directly next to the function when calling functions
function().When indexing or slicing the brackets should be directly next to the collection with no space
collection["index"].Whitespace used to line up variable values is not recommended.
Make sure you are consistent with the formats you choose when optional choices are available.
General advice
Get rid of as many
breakandcontinuestatements as possible.Write short functions. All functions should fit within a standard screen.
Use descriptive variable names.
Writing documentation in the code
Here is an example of how to write good docstrings:
The NumPy docstring documentation can be found here
C++
The customized Clang Format style is used for C++ code formatting. The style is defined in .clang-format file in the root of the repository. The style is based on the Google C++ style with some modifications.
Run scripts to check the code
It’s a good idea to install pre-commit on your repository:
$ pip install pre-commit
$ pre-commit install
The scripts will be run automatically before each commit and will fix the code style issues automatically.
CI/CD
CI
Test CUDA
Test CUDA action runs tests on a self-hosted runner with the NVIDIA card. It is not triggered by every PR. The developer who has the permission to manage the label can apply the label Test CUDA to a PR to trigger this action.
CD
GitHub Actions is used to build pre-compiled packages for each commit. See the Easy install the latest development version section to learn how to install the latest development version.
Python API
backend package
Submodules
backend.dp_backend module
backend.dynamic_metadata module
backend.find_tensorflow module
- backend.find_tensorflow.find_tensorflow() Tuple[Optional[str], List[str]][source]
Find TensorFlow library.
Tries to find TensorFlow in the order of:
Environment variable TENSORFLOW_ROOT if set
The current Python environment.
user site packages directory if enabled
system site packages directory (purelib)
add as a requirement (detect TENSORFLOW_VERSION or the latest) and let pip install it
backend.read_env module
Read environment variables to configure the build.
deepmd package
Root of the deepmd package, exposes all public classes and submodules.
- class deepmd.DeepEval(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
objectCommon methods for DeepPot, DeepWFC, DeepPolar, …
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:False If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList,optional The ASE neighbor list class to produce the neighbor list. If None, the neighbor list will be built natively in the model.
- model_file
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
Evaluate output of type embedding network by using this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- build_neighbor_list(coords: ndarray, cell: Optional[ndarray], atype: ndarray, imap: ndarray, neighbor_list)[source]
Make the mesh with neighbor list for a single frame.
- Parameters
- coords
np.ndarray The coordinates of atoms. Should be of shape [natoms, 3]
- cell
Optional[np.ndarray] The cell of the system. Should be of shape [3, 3]
- atype
np.ndarray The type of atoms. Should be of shape [natoms]
- imap
np.ndarray The index map of atoms. Should be of shape [natoms]
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList ASE neighbor list. The following method or attribute will be used/set: bothways, self_interaction, update, build, first_neigh, pair_second, offset_vec.
- coords
- Returns
- natoms_vec
np.ndarray The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: nloc natoms[1]: nall natoms[i]: 2 <= i < Ntypes+2, number of type i atoms for nloc
- coords
np.ndarray The coordinates of atoms, including ghost atoms. Should be of shape [nframes, nall, 3]
- atype
np.ndarray The type of atoms, including ghost atoms. Should be of shape [nall]
- mesh
np.ndarray The mesh in nei_mode=4.
- imap
np.ndarray The index map of atoms. Should be of shape [nall]
- ghost_map
np.ndarray The index map of ghost atoms. Should be of shape [nghost]
- natoms_vec
- eval_typeebd() ndarray[source]
Evaluate output of type embedding network by using this model.
- Returns
np.ndarrayThe output of type embedding network. The shape is [ntypes, o_size], where ntypes is the number of types, and o_size is the number of nodes in the output layer.
- Raises
KeyErrorIf the model does not enable type embedding.
See also
deepmd.utils.type_embed.TypeEmbedNetThe type embedding network.
Examples
Get the output of type embedding network of graph.pb:
>>> from deepmd.infer import DeepPotential >>> dp = DeepPotential('graph.pb') >>> dp.eval_typeebd()
- make_natoms_vec(atom_types: ndarray, mixed_type: bool = False) ndarray[source]
Make the natom vector used by deepmd-kit.
- Parameters
- atom_types
The type of atoms
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
natomsThe number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- static reverse_map(vec: ndarray, imap: List[int]) ndarray[source]
Reverse mapping of a vector according to the index map.
- Parameters
- vec
Input vector. Be of shape [nframes, natoms, -1]
- imap
Index map. Be of shape [natoms]
- Returns
vec_outReverse mapped vector.
- property sess: Session
Get TF session.
- static sort_input(coord: ndarray, atom_type: ndarray, sel_atoms: Optional[List[int]] = None, mixed_type: bool = False)[source]
Sort atoms in the system according their types.
- Parameters
- coord
The coordinates of atoms. Should be of shape [nframes, natoms, 3]
- atom_type
The type of atoms Should be of shape [natoms]
- sel_atoms
The selected atoms by type
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
coord_outThe coordinates after sorting
atom_type_outThe atom types after sorting
idx_mapThe index mapping from the input to the output. For example coord_out = coord[:,idx_map,:]
sel_atom_typeOnly output if sel_atoms is not None The sorted selected atom types
sel_idx_mapOnly output if sel_atoms is not None The index mapping from the selected atoms to sorted selected atoms.
- deepmd.DeepPotential(model_file: Union[str, Path], load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None) Union[DeepDipole, DeepGlobalPolar, DeepPolar, DeepPot, DeepDOS, DeepWFC][source]
Factory function that will inialize appropriate potential read from model_file.
- Parameters
- model_file
str The name of the frozen model file.
- load_prefix
str The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
- Returns
Union[DeepDipole,DeepGlobalPolar,DeepPolar,DeepPot,DeepWFC]one of the available potentials
- Raises
RuntimeErrorif model file does not correspond to any implementd potential
- class deepmd.DipoleChargeModifier(model_name: str, model_charge_map: List[float], sys_charge_map: List[float], ewald_h: float = 1, ewald_beta: float = 1)[source]
Bases:
DeepDipole- Parameters
- model_name
The model file for the DeepDipole model
- model_charge_map
Gives the amount of charge for the wfcc
- sys_charge_map
Gives the amount of charge for the real atoms
- ewald_h
Grid spacing of the reciprocal part of Ewald sum. Unit: A
- ewald_beta
Splitting parameter of the Ewald sum. Unit: A^{-1}
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
Build the computational graph for the force and virial inference.
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coord, box, atype[, eval_fv])Evaluate the modification.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
get_dim_aparam()Unsupported in this model.
get_dim_fparam()Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
modify_data(data, data_sys)Modify data.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coord: ndarray, box: ndarray, atype: ndarray, eval_fv: bool = True) Tuple[ndarray, ndarray, ndarray][source]
Evaluate the modification.
- Parameters
- coord
The coordinates of atoms
- box
The simulation region. PBC is assumed
- atype
The atom types
- eval_fv
Evaluate force and virial
- Returns
tot_eThe energy modification
tot_fThe force modification
tot_vThe virial modification
- modify_data(data: dict, data_sys: DeepmdData) None[source]
Modify data.
- Parameters
- data
Internal data of DeepmdData. Be a dict, has the following keys - coord coordinates - box simulation box - type atom types - find_energy tells if data has energy - find_force tells if data has force - find_virial tells if data has virial - energy energy - force force - virial virial
- data_sys
DeepmdData The data system.
Subpackages
deepmd.cluster package
Module that reads node resources, auto detects if running local or on SLURM.
- deepmd.cluster.get_resource() Tuple[str, List[str], Optional[List[int]]][source]
Get local or slurm resources: nodename, nodelist, and gpus.
Submodules
deepmd.cluster.local module
Get local GPU resources.
deepmd.cluster.slurm module
MOdule to get resources on SLURM cluster.
- deepmd.cluster.slurm.get_resource() Tuple[str, List[str], Optional[List[int]]][source]
Get SLURM resources: nodename, nodelist, and gpus.
- Returns
- Raises
RuntimeErrorif number of nodes could not be retrieved
ValueErrorlist of nodes is not of the same length sa number of nodes
ValueErrorif current nodename is not found in node list
deepmd.descriptor package
- class deepmd.descriptor.Descriptor(*args, **kwargs)[source]
Bases:
PluginVariantThe abstract class for descriptors. All specific descriptors should be based on this class.
The descriptor \(\mathcal{D}\) describes the environment of an atom, which should be a function of coordinates and types of its neighbour atoms.
Notes
Only methods and attributes defined in this class are generally public, that can be called by other classes.
Examples
>>> descript = Descriptor(type="se_e2_a", rcut=6., rcut_smth=0.5, sel=[50]) >>> type(descript) <class 'deepmd.descriptor.se_a.DescrptSeA'>
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- abstract build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: Dict[str, Any], reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
tf.Tensor The coordinate of atoms
- atype_
tf.Tensor The type of atoms
- natoms
tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of frames
- mesh
tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
dict[str,Any] Dictionary for additional inputs
- reusebool,
optional The weights in the networks should be reused when get the variable.
- suffix
str,optional Name suffix to identify this descriptor
- coord_
- Returns
- descriptor:
tf.Tensor The output descriptor
- descriptor:
Notes
This method must be implemented, as it’s called by other classes.
- build_type_exclude_mask(exclude_types: List[Tuple[int, int]], ntypes: int, sel: List[int], ndescrpt: int, atype: Tensor, shape0: Tensor) Tensor[source]
Build the type exclude mask for the descriptor.
- Parameters
- exclude_types
List[Tuple[int,int]] The list of excluded types, e.g. [(0, 1), (1, 0)] means the interaction between type 0 and type 1 is excluded.
- ntypes
int The number of types.
- sel
List[int] The list of the number of selected neighbors for each type.
- ndescrpt
int The number of descriptors for each atom.
- atype
tf.Tensor The type of atoms, with the size of shape0.
- shape0
tf.Tensor The shape of the first dimension of the inputs, which is equal to nsamples * natoms.
- exclude_types
- Returns
tf.TensorThe type exclude mask, with the shape of (shape0, ndescrpt), and the precision of GLOBAL_TF_FLOAT_PRECISION. The mask has the value of 1 if the interaction between two types is not excluded, and 0 otherwise.
Notes
To exclude the interaction between two types, the derivative of energy with respect to distances (or angles) between two atoms should be zero[R08579741114c-1]_, i.e.
\[\forall i \in \text{type 1}, j \in \text{type 2}, \frac{\partial{E}}{\partial{r_{ij}}} = 0\]When embedding networks between every two types are built, we can just remove that network. But when type_one_side is enabled, a network may be built for multiple pairs of types. In this case, we need to build a mask to exclude the interaction between two types.
The mask assumes the descriptors are sorted by neighbro type with the fixed number of given sel and each neighbor has the same number of descriptors (for example 4).
References
- 1
Jinzhe Zeng, Timothy J. Giese, ̧Sölen Ekesan, Darrin M. York, Development of Range-Corrected Deep Learning Potentials for Fast, Accurate Quantum Mechanical/molecular Mechanical Simulations of Chemical Reactions in Solution, J. Chem. Theory Comput., 2021, 17 (11), 6993-7009.
- abstract compute_input_stats(data_coord: List[ndarray], data_box: List[ndarray], data_atype: List[ndarray], natoms_vec: List[ndarray], mesh: List[ndarray], input_dict: Dict[str, List[ndarray]], **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
list[np.ndarray] The coordinates. Can be generated by
deepmd.model.model_stat.make_stat_input()- data_box
list[np.ndarray] The box. Can be generated by
deepmd.model.model_stat.make_stat_input()- data_atype
list[np.ndarray] The atom types. Can be generated by
deepmd.model.model_stat.make_stat_input()- natoms_vec
list[np.ndarray] The vector for the number of atoms of the system and different types of atoms. Can be generated by
deepmd.model.model_stat.make_stat_input()- mesh
list[np.ndarray] The mesh for neighbor searching. Can be generated by
deepmd.model.model_stat.make_stat_input()- input_dict
dict[str,list[np.ndarray]] Dictionary for additional input
- **kwargs
Additional keyword arguments which may contain mixed_type and real_natoms_vec.
- data_coord
Notes
This method must be implemented, as it’s called by other classes.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5.0, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
float The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph definition of the model
- table_extrapolate
float, default: 5. The scale of model extrapolation
- table_stride_1
float, default: 0.01 The uniform stride of the first table
- table_stride_2
float, default: 0.1 The uniform stride of the second table
- check_frequency
int, default: -1 The overflow check frequency
- suffix
str,optional The suffix of the scope
- min_nbor_dist
Notes
This method is called by others when the descriptor supported compression.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
Notes
This method is called by others when the descriptor supported compression.
- abstract get_dim_out() int[source]
Returns the output dimension of this descriptor.
- Returns
intthe output dimension of this descriptor
Notes
This method must be implemented, as it’s called by other classes.
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- Returns
intthe first dimension of the rotation matrix
- abstract get_ntypes() int[source]
Returns the number of atom types.
- Returns
intthe number of atom types
Notes
This method must be implemented, as it’s called by other classes.
- abstract get_rcut() float[source]
Returns the cut-off radius.
- Returns
floatthe cut-off radius
Notes
This method must be implemented, as it’s called by other classes.
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- Parameters
Notes
This method is called by others when the descriptor supported initialization from the given variables.
- pass_tensors_from_frz_model(*tensors: Tensor) None[source]
Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
- Parameters
- *tensors
tf.Tensor passed tensors
- *tensors
Notes
The number of parameters in the method must be equal to the numbers of returns in
get_tensor_names().
- abstract prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- Returns
- class deepmd.descriptor.DescrptHybrid(*args, **kwargs)[source]
Bases:
DescriptorConcate a list of descriptors to form a new descriptor.
- Parameters
- list
list Build a descriptor from the concatenation of the list of descriptors.
- list
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Get the neighbor information of the descriptor, returns the nlist of the descriptor with the largest cut-off radius.
get_nlist_i(ii)Get the neighbor information of the ii-th descriptor.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, mixed_type: bool = False, real_natoms_vec: Optional[list] = None, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- real_natoms_vec
If mixed_type is True, it takes in the real natoms_vec for each frame.
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5.0, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
float The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
float, default: 5. The scale of model extrapolation
- table_stride_1
float, default: 0.01 The uniform stride of the first table
- table_stride_2
float, default: 0.1 The uniform stride of the second table
- check_frequency
int, default: -1 The overflow check frequency
- suffix
str,optional The suffix of the scope
- min_nbor_dist
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Get the neighbor information of the descriptor, returns the nlist of the descriptor with the largest cut-off radius.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- get_nlist_i(ii: int) Tuple[Tensor, Tensor, List[int], List[int]][source]
Get the neighbor information of the ii-th descriptor.
- Parameters
- ii
int The index of the descriptor
- ii
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- pass_tensors_from_frz_model(*tensors: Tensor) None[source]
Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
- Parameters
- *tensors
tf.Tensor passed tensors
- *tensors
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.DescrptLocFrame(*args, **kwargs)[source]
Bases:
DescriptorDefines a local frame at each atom, and the compute the descriptor as local coordinates under this frame.
- Parameters
- rcut
The cut-off radius
- sel_a
list[int] The length of the list should be the same as the number of atom types in the system. sel_a[i] gives the selected number of type-i neighbors. The full relative coordinates of the neighbors are used by the descriptor.
- sel_r
list[int] The length of the list should be the same as the number of atom types in the system. sel_r[i] gives the selected number of type-i neighbors. Only relative distance of the neighbors are used by the descriptor. sel_a[i] + sel_r[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius.
- axis_rule: list[int]
The length should be 6 times of the number of types. - axis_rule[i*6+0]: class of the atom defining the first axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance. - axis_rule[i*6+1]: type of the atom defining the first axis of type-i atom. - axis_rule[i*6+2]: index of the axis atom defining the first axis. Note that the neighbors with the same class and type are sorted according to their relative distance. - axis_rule[i*6+3]: class of the atom defining the second axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance. - axis_rule[i*6+4]: type of the atom defining the second axis of type-i atom. - axis_rule[i*6+5]: index of the axis atom defining the second axis. Note that the neighbors with the same class and type are sorted according to their relative distance.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
- Returns
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.DescrptSeA(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net().- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- multi_task
If the model has multi fitting nets to train.
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.DescrptSeAEbd(*args, **kwargs)[source]
Bases:
DescrptSeADeepPot-SE descriptor with type embedding approach.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- axis_neuron
Number of the axis neuron (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- type_nchanl
Number of channels for type representation
- type_nlayer
Number of hidden layers for the type embedding net (skip connected).
- numb_aparam
Number of atomic parameters. If >0 it will be embedded with atom types.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are {0}
- precision
The precision of the embedding net parameters. Supported options are {1}
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- class deepmd.descriptor.DescrptSeAEbdV2(*args, **kwargs)[source]
Bases:
DescrptSeAA compressible se_a_ebd model.
This model is a warpper for DescriptorSeA, which set stripped_type_embedding=True.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- class deepmd.descriptor.DescrptSeAEf(*args, **kwargs)[source]
Bases:
DescrptSeSmooth edition descriptor with Ef.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- axis_neuron
Number of the axis neuron (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs. Should have ‘efield’.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.DescrptSeAEfLower(*args, **kwargs)[source]
Bases:
DescrptSeAHelper class for implementing DescrptSeAEf.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_, atype_, natoms, box_, mesh, input_dict, suffix='', reuse=None)[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord, data_box, data_atype, natoms_vec, mesh, input_dict, **kwargs)[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- class deepmd.descriptor.DescrptSeAMask(*args, **kwargs)[source]
Bases:
DescrptSeADeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net(). Specially for descriptor se_a_mask is a concise implementation of se_a. The difference is that se_a_mask only considered a non-pbc system. And accept a mask matrix to indicate the atom i in frame j is a real atom or not. (1 means real atom, 0 means ghost atom) Thus se_a_mask can accept a variable number of atoms in a frame.- Parameters
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the neighbor list.
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- activation_function
The activation function in the embedding net. Supported options are {0}
- precision
The precision of the embedding net parameters. Supported options are {1}
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- sel
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cutoff radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: Dict[str, Any], reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialNone for se_a_mask op
atom_virialNone for se_a_mask op
- class deepmd.descriptor.DescrptSeAtten(*args, **kwargs)[source]
Bases:
DescrptSeASmooth version descriptor with attention.
- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
int sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- attn
The length of hidden vector during scale-dot attention computation.
- attn_layer
The number of layers in attention mechanism.
- attn_dotr
Whether to dot the relative coordinates on the attention weights as a gated scheme.
- attn_mask
Whether to mask the diagonal in the attention weights.
- multi_task
If the model has multi fitting nets to train.
- stripped_type_embedding
Whether to strip the type embedding into a separated embedding network. Default value will be True in se_atten_v2 descriptor.
- smooth_type_embdding
When using stripped type embedding, whether to dot smooth factor on the network output of type embedding to keep the network smooth, instead of setting set_davg_zero to be True. Default value will be True in se_atten_v2 descriptor.
- Raises
ValueErrorif ntypes is 0.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the attention descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- build_type_exclude_mask(exclude_types: List[Tuple[int, int]], ntypes: int, sel: List[int], ndescrpt: int, atype: Tensor, shape0: Tensor, nei_type_vec: Tensor) Tensor[source]
Build the type exclude mask for the attention descriptor.
- Parameters
- exclude_types
List[Tuple[int,int]] The list of excluded types, e.g. [(0, 1), (1, 0)] means the interaction between type 0 and type 1 is excluded.
- ntypes
int The number of types.
- sel
List[int] The list of the number of selected neighbors for each type.
- ndescrpt
int The number of descriptors for each atom.
- atype
tf.Tensor The type of atoms, with the size of shape0.
- shape0
tf.Tensor The shape of the first dimension of the inputs, which is equal to nsamples * natoms.
- nei_type_vec
tf.Tensor The type of neighbors, with the size of (shape0, nnei).
- exclude_types
- Returns
tf.TensorThe type exclude mask, with the shape of (shape0, ndescrpt), and the precision of GLOBAL_TF_FLOAT_PRECISION. The mask has the value of 1 if the interaction between two types is not excluded, and 0 otherwise.
Notes
This method has the similiar way to build the type exclude mask as
deepmd.descriptor.descriptor.Descriptor.build_type_exclude_mask(). The mathmatical expression has been explained in that method. The difference is that the attention descriptor has provided the type of the neighbors (idx_j) that is not in order, so we use it from an extra input.
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, mixed_type: bool = False, real_natoms_vec: Optional[list] = None, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. If mixed_type is True, this para is blank. See real_natoms_vec.
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- real_natoms_vec
If mixed_type is True, it takes in the real natoms_vec for each frame.
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- class deepmd.descriptor.DescrptSeAttenV2(*args, **kwargs)[source]
Bases:
DescrptSeAttenSmooth version 2.0 descriptor with attention.
- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
int sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- attn
The length of hidden vector during scale-dot attention computation.
- attn_layer
The number of layers in attention mechanism.
- attn_dotr
Whether to dot the relative coordinates on the attention weights as a gated scheme.
- attn_mask
Whether to mask the diagonal in the attention weights.
- multi_task
If the model has multi fitting nets to train.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the attention descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- class deepmd.descriptor.DescrptSeR(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from radial information of atomic configurations.
The embedding takes the distance between atoms as input.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord, data_box, data_atype, natoms_vec, mesh, input_dict, **kwargs)[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- get_nlist()[source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.DescrptSeT(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from all information (both angular and radial) of atomic configurations.
The embedding takes angles between two neighboring atoms as input.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
Submodules
deepmd.descriptor.descriptor module
- class deepmd.descriptor.descriptor.Descriptor(*args, **kwargs)[source]
Bases:
PluginVariantThe abstract class for descriptors. All specific descriptors should be based on this class.
The descriptor \(\mathcal{D}\) describes the environment of an atom, which should be a function of coordinates and types of its neighbour atoms.
Notes
Only methods and attributes defined in this class are generally public, that can be called by other classes.
Examples
>>> descript = Descriptor(type="se_e2_a", rcut=6., rcut_smth=0.5, sel=[50]) >>> type(descript) <class 'deepmd.descriptor.se_a.DescrptSeA'>
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- abstract build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: Dict[str, Any], reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
tf.Tensor The coordinate of atoms
- atype_
tf.Tensor The type of atoms
- natoms
tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of frames
- mesh
tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
dict[str,Any] Dictionary for additional inputs
- reusebool,
optional The weights in the networks should be reused when get the variable.
- suffix
str,optional Name suffix to identify this descriptor
- coord_
- Returns
- descriptor:
tf.Tensor The output descriptor
- descriptor:
Notes
This method must be implemented, as it’s called by other classes.
- build_type_exclude_mask(exclude_types: List[Tuple[int, int]], ntypes: int, sel: List[int], ndescrpt: int, atype: Tensor, shape0: Tensor) Tensor[source]
Build the type exclude mask for the descriptor.
- Parameters
- exclude_types
List[Tuple[int,int]] The list of excluded types, e.g. [(0, 1), (1, 0)] means the interaction between type 0 and type 1 is excluded.
- ntypes
int The number of types.
- sel
List[int] The list of the number of selected neighbors for each type.
- ndescrpt
int The number of descriptors for each atom.
- atype
tf.Tensor The type of atoms, with the size of shape0.
- shape0
tf.Tensor The shape of the first dimension of the inputs, which is equal to nsamples * natoms.
- exclude_types
- Returns
tf.TensorThe type exclude mask, with the shape of (shape0, ndescrpt), and the precision of GLOBAL_TF_FLOAT_PRECISION. The mask has the value of 1 if the interaction between two types is not excluded, and 0 otherwise.
Notes
To exclude the interaction between two types, the derivative of energy with respect to distances (or angles) between two atoms should be zero[Rafc1ae60e195-1]_, i.e.
\[\forall i \in \text{type 1}, j \in \text{type 2}, \frac{\partial{E}}{\partial{r_{ij}}} = 0\]When embedding networks between every two types are built, we can just remove that network. But when type_one_side is enabled, a network may be built for multiple pairs of types. In this case, we need to build a mask to exclude the interaction between two types.
The mask assumes the descriptors are sorted by neighbro type with the fixed number of given sel and each neighbor has the same number of descriptors (for example 4).
References
- 1
Jinzhe Zeng, Timothy J. Giese, ̧Sölen Ekesan, Darrin M. York, Development of Range-Corrected Deep Learning Potentials for Fast, Accurate Quantum Mechanical/molecular Mechanical Simulations of Chemical Reactions in Solution, J. Chem. Theory Comput., 2021, 17 (11), 6993-7009.
- abstract compute_input_stats(data_coord: List[ndarray], data_box: List[ndarray], data_atype: List[ndarray], natoms_vec: List[ndarray], mesh: List[ndarray], input_dict: Dict[str, List[ndarray]], **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
list[np.ndarray] The coordinates. Can be generated by
deepmd.model.model_stat.make_stat_input()- data_box
list[np.ndarray] The box. Can be generated by
deepmd.model.model_stat.make_stat_input()- data_atype
list[np.ndarray] The atom types. Can be generated by
deepmd.model.model_stat.make_stat_input()- natoms_vec
list[np.ndarray] The vector for the number of atoms of the system and different types of atoms. Can be generated by
deepmd.model.model_stat.make_stat_input()- mesh
list[np.ndarray] The mesh for neighbor searching. Can be generated by
deepmd.model.model_stat.make_stat_input()- input_dict
dict[str,list[np.ndarray]] Dictionary for additional input
- **kwargs
Additional keyword arguments which may contain mixed_type and real_natoms_vec.
- data_coord
Notes
This method must be implemented, as it’s called by other classes.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5.0, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
float The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph definition of the model
- table_extrapolate
float, default: 5. The scale of model extrapolation
- table_stride_1
float, default: 0.01 The uniform stride of the first table
- table_stride_2
float, default: 0.1 The uniform stride of the second table
- check_frequency
int, default: -1 The overflow check frequency
- suffix
str,optional The suffix of the scope
- min_nbor_dist
Notes
This method is called by others when the descriptor supported compression.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
Notes
This method is called by others when the descriptor supported compression.
- abstract get_dim_out() int[source]
Returns the output dimension of this descriptor.
- Returns
intthe output dimension of this descriptor
Notes
This method must be implemented, as it’s called by other classes.
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- Returns
intthe first dimension of the rotation matrix
- abstract get_ntypes() int[source]
Returns the number of atom types.
- Returns
intthe number of atom types
Notes
This method must be implemented, as it’s called by other classes.
- abstract get_rcut() float[source]
Returns the cut-off radius.
- Returns
floatthe cut-off radius
Notes
This method must be implemented, as it’s called by other classes.
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- Parameters
Notes
This method is called by others when the descriptor supported initialization from the given variables.
- pass_tensors_from_frz_model(*tensors: Tensor) None[source]
Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
- Parameters
- *tensors
tf.Tensor passed tensors
- *tensors
Notes
The number of parameters in the method must be equal to the numbers of returns in
get_tensor_names().
- abstract prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- Returns
deepmd.descriptor.hybrid module
- class deepmd.descriptor.hybrid.DescrptHybrid(*args, **kwargs)[source]
Bases:
DescriptorConcate a list of descriptors to form a new descriptor.
- Parameters
- list
list Build a descriptor from the concatenation of the list of descriptors.
- list
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Get the neighbor information of the descriptor, returns the nlist of the descriptor with the largest cut-off radius.
get_nlist_i(ii)Get the neighbor information of the ii-th descriptor.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, mixed_type: bool = False, real_natoms_vec: Optional[list] = None, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- real_natoms_vec
If mixed_type is True, it takes in the real natoms_vec for each frame.
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5.0, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
float The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
float, default: 5. The scale of model extrapolation
- table_stride_1
float, default: 0.01 The uniform stride of the first table
- table_stride_2
float, default: 0.1 The uniform stride of the second table
- check_frequency
int, default: -1 The overflow check frequency
- suffix
str,optional The suffix of the scope
- min_nbor_dist
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Get the neighbor information of the descriptor, returns the nlist of the descriptor with the largest cut-off radius.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- get_nlist_i(ii: int) Tuple[Tensor, Tensor, List[int], List[int]][source]
Get the neighbor information of the ii-th descriptor.
- Parameters
- ii
int The index of the descriptor
- ii
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- pass_tensors_from_frz_model(*tensors: Tensor) None[source]
Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
- Parameters
- *tensors
tf.Tensor passed tensors
- *tensors
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
deepmd.descriptor.loc_frame module
- class deepmd.descriptor.loc_frame.DescrptLocFrame(*args, **kwargs)[source]
Bases:
DescriptorDefines a local frame at each atom, and the compute the descriptor as local coordinates under this frame.
- Parameters
- rcut
The cut-off radius
- sel_a
list[int] The length of the list should be the same as the number of atom types in the system. sel_a[i] gives the selected number of type-i neighbors. The full relative coordinates of the neighbors are used by the descriptor.
- sel_r
list[int] The length of the list should be the same as the number of atom types in the system. sel_r[i] gives the selected number of type-i neighbors. Only relative distance of the neighbors are used by the descriptor. sel_a[i] + sel_r[i] is recommended to be larger than the maximally possible number of type-i neighbors in the cut-off radius.
- axis_rule: list[int]
The length should be 6 times of the number of types. - axis_rule[i*6+0]: class of the atom defining the first axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance. - axis_rule[i*6+1]: type of the atom defining the first axis of type-i atom. - axis_rule[i*6+2]: index of the axis atom defining the first axis. Note that the neighbors with the same class and type are sorted according to their relative distance. - axis_rule[i*6+3]: class of the atom defining the second axis of type-i atom. 0 for neighbors with full coordinates and 1 for neighbors only with relative distance. - axis_rule[i*6+4]: type of the atom defining the second axis of type-i atom. - axis_rule[i*6+5]: index of the axis atom defining the second axis. Note that the neighbors with the same class and type are sorted according to their relative distance.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
- Returns
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(*tensors)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
deepmd.descriptor.se module
- class deepmd.descriptor.se.DescrptSe(*args, **kwargs)[source]
Bases:
DescriptorA base class for smooth version of descriptors.
Notes
All of these descriptors have an environmental matrix and an embedding network (
deepmd.utils.network.embedding_net()), so they can share some similiar methods without defining them twice.- Attributes
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- pass_tensors_from_frz_model(descrpt_reshape: Tensor, descrpt_deriv: Tensor, rij: Tensor, nlist: Tensor)[source]
Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
- Parameters
- descrpt_reshape
The passed descrpt_reshape tensor
- descrpt_deriv
The passed descrpt_deriv tensor
- rij
The passed rij tensor
- nlist
The passed nlist tensor
- property precision: DType
Precision of filter network.
deepmd.descriptor.se_a module
- class deepmd.descriptor.se_a.DescrptSeA(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net().- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- multi_task
If the model has multi fitting nets to train.
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the embedding net variables with the given dict.
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
deepmd.descriptor.se_a_ebd module
- class deepmd.descriptor.se_a_ebd.DescrptSeAEbd(*args, **kwargs)[source]
Bases:
DescrptSeADeepPot-SE descriptor with type embedding approach.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- axis_neuron
Number of the axis neuron (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- type_nchanl
Number of channels for type representation
- type_nlayer
Number of hidden layers for the type embedding net (skip connected).
- numb_aparam
Number of atomic parameters. If >0 it will be embedded with atom types.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are {0}
- precision
The precision of the embedding net parameters. Supported options are {1}
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
deepmd.descriptor.se_a_ebd_v2 module
- class deepmd.descriptor.se_a_ebd_v2.DescrptSeAEbdV2(*args, **kwargs)[source]
Bases:
DescrptSeAA compressible se_a_ebd model.
This model is a warpper for DescriptorSeA, which set stripped_type_embedding=True.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
deepmd.descriptor.se_a_ef module
- class deepmd.descriptor.se_a_ef.DescrptSeAEf(*args, **kwargs)[source]
Bases:
DescrptSeSmooth edition descriptor with Ef.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- axis_neuron
Number of the axis neuron (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs. Should have ‘efield’.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- get_dim_rot_mat_1() int[source]
Returns the first dimension of the rotation matrix. The rotation is of shape dim_1 x 3.
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
- class deepmd.descriptor.se_a_ef.DescrptSeAEfLower(*args, **kwargs)[source]
Bases:
DescrptSeAHelper class for implementing DescrptSeAEf.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_, atype_, natoms, box_, mesh, input_dict, suffix='', reuse=None)[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord, data_box, data_atype, natoms_vec, mesh, input_dict, **kwargs)[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
deepmd.descriptor.se_a_mask module
- class deepmd.descriptor.se_a_mask.DescrptSeAMask(*args, **kwargs)[source]
Bases:
DescrptSeADeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net(). Specially for descriptor se_a_mask is a concise implementation of se_a. The difference is that se_a_mask only considered a non-pbc system. And accept a mask matrix to indicate the atom i in frame j is a real atom or not. (1 means real atom, 0 means ghost atom) Thus se_a_mask can accept a variable number of atoms in a frame.- Parameters
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the neighbor list.
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- activation_function
The activation function in the embedding net. Supported options are {0}
- precision
The precision of the embedding net parameters. Supported options are {1}
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- sel
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cutoff radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: Dict[str, Any], reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialNone for se_a_mask op
atom_virialNone for se_a_mask op
deepmd.descriptor.se_atten module
- class deepmd.descriptor.se_atten.DescrptSeAtten(*args, **kwargs)[source]
Bases:
DescrptSeASmooth version descriptor with attention.
- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
int sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- attn
The length of hidden vector during scale-dot attention computation.
- attn_layer
The number of layers in attention mechanism.
- attn_dotr
Whether to dot the relative coordinates on the attention weights as a gated scheme.
- attn_mask
Whether to mask the diagonal in the attention weights.
- multi_task
If the model has multi fitting nets to train.
- stripped_type_embedding
Whether to strip the type embedding into a separated embedding network. Default value will be True in se_atten_v2 descriptor.
- smooth_type_embdding
When using stripped type embedding, whether to dot smooth factor on the network output of type embedding to keep the network smooth, instead of setting set_davg_zero to be True. Default value will be True in se_atten_v2 descriptor.
- Raises
ValueErrorif ntypes is 0.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the attention descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- build_type_exclude_mask(exclude_types: List[Tuple[int, int]], ntypes: int, sel: List[int], ndescrpt: int, atype: Tensor, shape0: Tensor, nei_type_vec: Tensor) Tensor[source]
Build the type exclude mask for the attention descriptor.
- Parameters
- exclude_types
List[Tuple[int,int]] The list of excluded types, e.g. [(0, 1), (1, 0)] means the interaction between type 0 and type 1 is excluded.
- ntypes
int The number of types.
- sel
List[int] The list of the number of selected neighbors for each type.
- ndescrpt
int The number of descriptors for each atom.
- atype
tf.Tensor The type of atoms, with the size of shape0.
- shape0
tf.Tensor The shape of the first dimension of the inputs, which is equal to nsamples * natoms.
- nei_type_vec
tf.Tensor The type of neighbors, with the size of (shape0, nnei).
- exclude_types
- Returns
tf.TensorThe type exclude mask, with the shape of (shape0, ndescrpt), and the precision of GLOBAL_TF_FLOAT_PRECISION. The mask has the value of 1 if the interaction between two types is not excluded, and 0 otherwise.
Notes
This method has the similiar way to build the type exclude mask as
deepmd.descriptor.descriptor.Descriptor.build_type_exclude_mask(). The mathmatical expression has been explained in that method. The difference is that the attention descriptor has provided the type of the neighbors (idx_j) that is not in order, so we use it from an extra input.
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, mixed_type: bool = False, real_natoms_vec: Optional[list] = None, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. If mixed_type is True, this para is blank. See real_natoms_vec.
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- real_natoms_vec
If mixed_type is True, it takes in the real natoms_vec for each frame.
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
deepmd.descriptor.se_atten_v2 module
- class deepmd.descriptor.se_atten_v2.DescrptSeAttenV2(*args, **kwargs)[source]
Bases:
DescrptSeAttenSmooth version 2.0 descriptor with attention.
- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
int sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- attn
The length of hidden vector during scale-dot attention computation.
- attn_layer
The number of layers in attention mechanism.
- attn_dotr
Whether to dot the relative coordinates on the attention weights as a gated scheme.
- attn_mask
Whether to mask the diagonal in the attention weights.
- multi_task
If the model has multi fitting nets to train.
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the attention descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_dim_out()Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
get_nlist()Returns neighbor information.
get_ntypes()Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_rot_mat()Get rotational matrix.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
deepmd.descriptor.se_r module
- class deepmd.descriptor.se_r.DescrptSeR(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from radial information of atomic configurations.
The embedding takes the distance between atoms as input.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord, data_box, data_atype, natoms_vec, mesh, input_dict, **kwargs)[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- get_nlist()[source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
deepmd.descriptor.se_t module
- class deepmd.descriptor.se_t.DescrptSeT(*args, **kwargs)[source]
Bases:
DescrptSeDeepPot-SE constructed from all information (both angular and radial) of atomic configurations.
The embedding takes angles between two neighboring atoms as input.
- Parameters
- rcut
The cut-off radius
- rcut_smth
From where the environment matrix should be smoothed
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- Attributes
explicit_ntypesExplicit ntypes with type embedding.
precisionPrecision of filter network.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the computational graph for the descriptor.
build_type_exclude_mask(exclude_types, ...)Build the type exclude mask for the descriptor.
compute_input_stats(data_coord, data_box, ...)Compute the statisitcs (avg and std) of the training data.
enable_compression(min_nbor_dist, graph, ...)Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
Returns the output dimension of this descriptor.
get_dim_rot_mat_1()Returns the first dimension of the rotation matrix.
Returns neighbor information.
Returns the number of atom types.
get_rcut()Returns the cut-off radius.
get_tensor_names([suffix])Get names of tensors.
init_variables(graph, graph_def[, suffix])Init the embedding net variables with the given dict.
merge_input_stats(stat_dict)Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
pass_tensors_from_frz_model(descrpt_reshape, ...)Pass the descrpt_reshape tensor as well as descrpt_deriv tensor from the frz graph_def.
prod_force_virial(atom_ener, natoms)Compute force and virial.
register(key)Register a descriptor plugin.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_class_by_input
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for the descriptor.
- Parameters
- coord_
The coordinate of atoms
- atype_
The type of atoms
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box_
tf.Tensor The box of the system
- mesh
For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- input_dict
Dictionary for additional inputs
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
descriptorThe output descriptor
- compute_input_stats(data_coord: list, data_box: list, data_atype: list, natoms_vec: list, mesh: list, input_dict: dict, **kwargs) None[source]
Compute the statisitcs (avg and std) of the training data. The input will be normalized by the statistics.
- Parameters
- data_coord
The coordinates. Can be generated by deepmd.model.make_stat_input
- data_box
The box. Can be generated by deepmd.model.make_stat_input
- data_atype
The atom types. Can be generated by deepmd.model.make_stat_input
- natoms_vec
The vector for the number of atoms of the system and different types of atoms. Can be generated by deepmd.model.make_stat_input
- mesh
The mesh for neighbor searching. Can be generated by deepmd.model.make_stat_input
- input_dict
Dictionary for additional input
- **kwargs
Additional keyword arguments.
- enable_compression(min_nbor_dist: float, graph: Graph, graph_def: GraphDef, table_extrapolate: float = 5, table_stride_1: float = 0.01, table_stride_2: float = 0.1, check_frequency: int = -1, suffix: str = '') None[source]
Reveive the statisitcs (distance, max_nbor_size and env_mat_range) of the training data.
- Parameters
- min_nbor_dist
The nearest distance between atoms
- graph
tf.Graph The graph of the model
- graph_def
tf.GraphDef The graph_def of the model
- table_extrapolate
The scale of model extrapolation
- table_stride_1
The uniform stride of the first table
- table_stride_2
The uniform stride of the second table
- check_frequency
The overflow check frequency
- suffix
str,optional The suffix of the scope
- get_nlist() Tuple[Tensor, Tensor, List[int], List[int]][source]
Returns neighbor information.
- Returns
nlistNeighbor list
rijThe relative distance between the neighbor and the center atom.
sel_aThe number of neighbors with full information
sel_rThe number of neighbors with only radial information
- merge_input_stats(stat_dict)[source]
Merge the statisitcs computed from compute_input_stats to obtain the self.davg and self.dstd.
- Parameters
- stat_dict
The dict of statisitcs computed from compute_input_stats, including:
- sumr
The sum of radial statisitcs.
- suma
The sum of relative coord statisitcs.
- sumn
The sum of neighbor numbers.
- sumr2
The sum of square of radial statisitcs.
- suma2
The sum of square of relative coord statisitcs.
- prod_force_virial(atom_ener: Tensor, natoms: Tensor) Tuple[Tensor, Tensor, Tensor][source]
Compute force and virial.
- Parameters
- atom_ener
The atomic energy
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- Returns
forceThe force on atoms
virialThe total virial
atom_virialThe atomic virial
deepmd.entrypoints package
Submodule that contains all the DeePMD-Kit entry point scripts.
- deepmd.entrypoints.compress(*, input: str, output: str, extrapolate: int, step: float, frequency: str, checkpoint_folder: str, training_script: str, mpi_log: str, log_path: Optional[str], log_level: int, **kwargs)[source]
Compress model.
The table is composed of fifth-order polynomial coefficients and is assembled from two sub-tables. The first table takes the step parameter as the domain’s uniform step size, while the second table takes 10 * step as it’s uniform step size. The range of the first table is automatically detected by the code, while the second table ranges from the first table’s upper boundary(upper) to the extrapolate(parameter) * upper.
- Parameters
- input
str frozen model file to compress
- output
str compressed model filename
- extrapolate
int scale of model extrapolation
- step
float uniform step size of the tabulation’s first table
- frequency
str frequency of tabulation overflow check
- checkpoint_folder
str trining checkpoint folder for freezing
- training_script
str training script of the input frozen model
- mpi_log
str mpi logging mode for training
- log_path
Optional[str] if speccified log will be written to this file
- log_level
int logging level
- **kwargs
additional arguments
- input
- deepmd.entrypoints.doc_train_input(*, out_type: str = 'rst', **kwargs)[source]
Print out trining input arguments to console.
- deepmd.entrypoints.freeze(*, checkpoint_folder: str, output: str, node_names: Optional[str] = None, nvnmd_weight: Optional[str] = None, united_model: bool = False, **kwargs)[source]
Freeze the graph in supplied folder.
- Parameters
- checkpoint_folder
str location of either the folder with checkpoint or the checkpoint prefix
- output
str output file name
- node_names
Optional[str],optional names of nodes to output, by default None
- nvnmd_weight
Optional[str],optional nvnmd weight file
- united_modelbool
when in multi-task mode, freeze all nodes into one unit model
- **kwargs
other arguments
- checkpoint_folder
- deepmd.entrypoints.make_model_devi(*, models: list, system: str, set_prefix: str, output: str, frequency: int, real_error: bool = False, atomic: bool = False, relative: Optional[float] = None, relative_v: Optional[float] = None, **kwargs)[source]
Make model deviation calculation.
- Parameters
- models
list A list of paths of models to use for making model deviation
- system
str The path of system to make model deviation calculation
- set_prefix
str The set prefix of the system
- output
str The output file for model deviation results
- frequency
int The number of steps that elapse between writing coordinates in a trajectory by a MD engine (such as Gromacs / Lammps). This paramter is used to determine the index in the output file.
- real_errorbool, default:
False If True, calculate the RMS real error instead of model deviation.
- atomicbool, default:
False If True, calculate the force model deviation of each atom.
- relative
float, default:None If given, calculate the relative model deviation of force. The value is the level parameter for computing the relative model deviation of the force.
- relative_v
float, default:None If given, calculate the relative model deviation of virial. The value is the level parameter for computing the relative model deviation of the virial.
- **kwargs
Arbitrary keyword arguments.
- models
- deepmd.entrypoints.neighbor_stat(*, system: str, rcut: float, type_map: List[str], one_type: bool = False, **kwargs)[source]
Calculate neighbor statistics.
- Parameters
Examples
>>> neighbor_stat(system='.', rcut=6., type_map=["C", "H", "O", "N", "P", "S", "Mg", "Na", "HW", "OW", "mNa", "mCl", "mC", "mH", "mMg", "mN", "mO", "mP"]) min_nbor_dist: 0.6599510670195264 max_nbor_size: [23, 26, 19, 16, 2, 2, 1, 1, 72, 37, 5, 0, 31, 29, 1, 21, 20, 5]
- deepmd.entrypoints.start_dpgui(*, port: int, bind_all: bool, **kwargs)[source]
Host DP-GUI server.
- Parameters
- Raises
ModuleNotFoundErrorThe dpgui package is not installed
- deepmd.entrypoints.test(*, model: str, system: str, datafile: str, set_prefix: str, numb_test: int, rand_seed: Optional[int], shuffle_test: bool, detail_file: str, atomic: bool, **kwargs)[source]
Test model predictions.
- Parameters
- model
str path where model is stored
- system
str system directory
- datafile
str the path to the list of systems to test
- set_prefix
str string prefix of set
- numb_test
int munber of tests to do. 0 means all data.
- rand_seed
Optional[int] seed for random generator
- shuffle_testbool
whether to shuffle tests
- detail_file
Optional[str] file where test details will be output
- atomicbool
whether per atom quantities should be computed
- **kwargs
additional arguments
- model
- Raises
RuntimeErrorif no valid system was found
- deepmd.entrypoints.train_dp(*, INPUT: str, init_model: Optional[str], restart: Optional[str], output: str, init_frz_model: str, mpi_log: str, log_level: int, log_path: Optional[str], is_compress: bool = False, skip_neighbor_stat: bool = False, finetune: Optional[str] = None, **kwargs)
Run DeePMD model training.
- Parameters
- INPUT
str json/yaml control file
- init_model
Optional[str] path prefix of checkpoint files or None
- restart
Optional[str] path prefix of checkpoint files or None
- output
str path for dump file with arguments
- init_frz_model
str path to frozen model or None
- mpi_log
str mpi logging mode
- log_level
int logging level defined by int 0-3
- log_path
Optional[str] logging file path or None if logs are to be output only to stdout
- is_compressbool
indicates whether in the model compress mode
- skip_neighbor_statbool, default=False
skip checking neighbor statistics
- finetune
Optional[str] path to pretrained model or None
- **kwargs
additional arguments
- INPUT
- Raises
RuntimeErrorif distributed training job name is wrong
- deepmd.entrypoints.transfer(*, old_model: str, raw_model: str, output: str, **kwargs)[source]
Transfer operation from old fron graph to new prepared raw graph.
Submodules
deepmd.entrypoints.compress module
Compress a model, which including tabulating the embedding-net.
- deepmd.entrypoints.compress.compress(*, input: str, output: str, extrapolate: int, step: float, frequency: str, checkpoint_folder: str, training_script: str, mpi_log: str, log_path: Optional[str], log_level: int, **kwargs)[source]
Compress model.
The table is composed of fifth-order polynomial coefficients and is assembled from two sub-tables. The first table takes the step parameter as the domain’s uniform step size, while the second table takes 10 * step as it’s uniform step size. The range of the first table is automatically detected by the code, while the second table ranges from the first table’s upper boundary(upper) to the extrapolate(parameter) * upper.
- Parameters
- input
str frozen model file to compress
- output
str compressed model filename
- extrapolate
int scale of model extrapolation
- step
float uniform step size of the tabulation’s first table
- frequency
str frequency of tabulation overflow check
- checkpoint_folder
str trining checkpoint folder for freezing
- training_script
str training script of the input frozen model
- mpi_log
str mpi logging mode for training
- log_path
Optional[str] if speccified log will be written to this file
- log_level
int logging level
- **kwargs
additional arguments
- input
deepmd.entrypoints.convert module
deepmd.entrypoints.doc module
deepmd.entrypoints.freeze module
Script for freezing TF trained graph so it can be used with LAMMPS and i-PI.
- deepmd.entrypoints.freeze.freeze(*, checkpoint_folder: str, output: str, node_names: Optional[str] = None, nvnmd_weight: Optional[str] = None, united_model: bool = False, **kwargs)[source]
Freeze the graph in supplied folder.
- Parameters
- checkpoint_folder
str location of either the folder with checkpoint or the checkpoint prefix
- output
str output file name
- node_names
Optional[str],optional names of nodes to output, by default None
- nvnmd_weight
Optional[str],optional nvnmd weight file
- united_modelbool
when in multi-task mode, freeze all nodes into one unit model
- **kwargs
other arguments
- checkpoint_folder
deepmd.entrypoints.gui module
- deepmd.entrypoints.gui.start_dpgui(*, port: int, bind_all: bool, **kwargs)[source]
Host DP-GUI server.
- Parameters
- Raises
ModuleNotFoundErrorThe dpgui package is not installed
deepmd.entrypoints.ipi module
Use dp_ipi inside the Python package.
deepmd.entrypoints.main module
DeePMD-Kit entry point module.
- deepmd.entrypoints.main.main(args: Optional[Union[List[str], Namespace]] = None)[source]
DeePMD-Kit entry point.
- Parameters
- args
List[str]orargparse.Namespace,optional list of command line arguments, used to avoid calling from the subprocess, as it is quite slow to import tensorflow; if Namespace is given, it will be used directly
- args
- Raises
RuntimeErrorif no command was input
- deepmd.entrypoints.main.main_parser() ArgumentParser[source]
DeePMD-Kit commandline options argument parser.
- Returns
argparse.ArgumentParsermain parser of DeePMD-kit
deepmd.entrypoints.neighbor_stat module
- deepmd.entrypoints.neighbor_stat.neighbor_stat(*, system: str, rcut: float, type_map: List[str], one_type: bool = False, **kwargs)[source]
Calculate neighbor statistics.
- Parameters
Examples
>>> neighbor_stat(system='.', rcut=6., type_map=["C", "H", "O", "N", "P", "S", "Mg", "Na", "HW", "OW", "mNa", "mCl", "mC", "mH", "mMg", "mN", "mO", "mP"]) min_nbor_dist: 0.6599510670195264 max_nbor_size: [23, 26, 19, 16, 2, 2, 1, 1, 72, 37, 5, 0, 31, 29, 1, 21, 20, 5]
deepmd.entrypoints.test module
Test trained DeePMD model.
- deepmd.entrypoints.test.test(*, model: str, system: str, datafile: str, set_prefix: str, numb_test: int, rand_seed: Optional[int], shuffle_test: bool, detail_file: str, atomic: bool, **kwargs)[source]
Test model predictions.
- Parameters
- model
str path where model is stored
- system
str system directory
- datafile
str the path to the list of systems to test
- set_prefix
str string prefix of set
- numb_test
int munber of tests to do. 0 means all data.
- rand_seed
Optional[int] seed for random generator
- shuffle_testbool
whether to shuffle tests
- detail_file
Optional[str] file where test details will be output
- atomicbool
whether per atom quantities should be computed
- **kwargs
additional arguments
- model
- Raises
RuntimeErrorif no valid system was found
deepmd.entrypoints.train module
DeePMD training entrypoint script.
Can handle local or distributed training.
- deepmd.entrypoints.train.train(*, INPUT: str, init_model: Optional[str], restart: Optional[str], output: str, init_frz_model: str, mpi_log: str, log_level: int, log_path: Optional[str], is_compress: bool = False, skip_neighbor_stat: bool = False, finetune: Optional[str] = None, **kwargs)[source]
Run DeePMD model training.
- Parameters
- INPUT
str json/yaml control file
- init_model
Optional[str] path prefix of checkpoint files or None
- restart
Optional[str] path prefix of checkpoint files or None
- output
str path for dump file with arguments
- init_frz_model
str path to frozen model or None
- mpi_log
str mpi logging mode
- log_level
int logging level defined by int 0-3
- log_path
Optional[str] logging file path or None if logs are to be output only to stdout
- is_compressbool
indicates whether in the model compress mode
- skip_neighbor_statbool, default=False
skip checking neighbor statistics
- finetune
Optional[str] path to pretrained model or None
- **kwargs
additional arguments
- INPUT
- Raises
RuntimeErrorif distributed training job name is wrong
deepmd.entrypoints.transfer module
Module used for transfering parameters between models.
deepmd.fit package
- class deepmd.fit.DOSFitting(*args, **kwargs)[source]
Bases:
FittingFitting the density of states (DOS) of the system. The energy should be shifted by the fermi level.
- Parameters
- descrpt
The descrptor \(\mathcal{D}\)
- neuron
Number of neurons \(N\) in each hidden layer of the fitting net
- resnet_dt
Time-step dt in the resnet construction: \(y = x + dt * \phi (Wx + b)\)
- numb_fparam
Number of frame parameter
- numb_aparam
Number of atomic parameter
- ! numb_dos (added)
Number of gridpoints on which the DOS is evaluated (NEDOS in VASP)
- rcond
The condition number for the regression of atomic energy.
- trainable
If the weights of fitting net are trainable. Suppose that we have \(N_l\) hidden layers in the fitting net, this list is of length \(N_l + 1\), specifying if the hidden layers and the output layer are trainable.
- seed
Random seed for initializing the network parameters.
- activation_function
The activation function \(\boldsymbol{\phi}\) in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- layer_name
list[Optional[str]],optional The name of the each layer. If two layers, either in the same fitting or different fittings, have the same name, they will share the same neural network parameters.
- use_aparam_as_mask: bool, optional
If True, the atomic parameters will be used as a mask that determines the atom is real/virtual. And the aparam will not be used as the atomic parameters for embedding.
- Attributes
precisionPrecision of fitting network.
Methods
build(inputs, natoms[, input_dict, reuse, ...])Build the computational graph for fitting net.
compute_input_stats(all_stat[, protection])Compute the input statistics.
compute_output_stats(all_stat[, mixed_type])Compute the ouput statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(inputs: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- inputs
The input descriptor
- input_dict
Additional dict for inputs. if numb_fparam > 0, should have input_dict[‘fparam’] if numb_aparam > 0, should have input_dict[‘aparam’]
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
enerThe system energy
- compute_input_stats(all_stat: dict, protection: float = 0.01) None[source]
Compute the input statistics.
- Parameters
- all_stat
if numb_fparam > 0 must have all_stat[‘fparam’] if numb_aparam > 0 must have all_stat[‘aparam’] can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
- compute_output_stats(all_stat: dict, mixed_type: bool = False) None[source]
Compute the ouput statistics.
- Parameters
- all_stat
must have the following components: all_stat[‘dos’] of shape n_sys x n_batch x n_frame x numb_dos can be prepared by model.make_stat_input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- class deepmd.fit.DipoleFittingSeA(*args, **kwargs)[source]
Bases:
FittingFit the atomic dipole with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic dipole prediction. If is None, all atoms are selected.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- descrpt
- Attributes
precisionPrecision of fitting network.
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected type.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(input_d: Tensor, rot_mat: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
dipoleThe atomic dipole.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- class deepmd.fit.EnerFitting(*args, **kwargs)[source]
Bases:
FittingFitting the energy of the system. The force and the virial can also be trained.
The potential energy \(E\) is a fitting network function of the descriptor \(\mathcal{D}\):
\[E(\mathcal{D}) = \mathcal{L}^{(n)} \circ \mathcal{L}^{(n-1)} \circ \cdots \circ \mathcal{L}^{(1)} \circ \mathcal{L}^{(0)}\]The first \(n\) hidden layers \(\mathcal{L}^{(0)}, \cdots, \mathcal{L}^{(n-1)}\) are given by
\[\mathbf{y}=\mathcal{L}(\mathbf{x};\mathbf{w},\mathbf{b})= \boldsymbol{\phi}(\mathbf{x}^T\mathbf{w}+\mathbf{b})\]where \(\mathbf{x} \in \mathbb{R}^{N_1}\) is the input vector and \(\mathbf{y} \in \mathbb{R}^{N_2}\) is the output vector. \(\mathbf{w} \in \mathbb{R}^{N_1 \times N_2}\) and \(\mathbf{b} \in \mathbb{R}^{N_2}\) are weights and biases, respectively, both of which are trainable if trainable[i] is True. \(\boldsymbol{\phi}\) is the activation function.
The output layer \(\mathcal{L}^{(n)}\) is given by
\[\mathbf{y}=\mathcal{L}^{(n)}(\mathbf{x};\mathbf{w},\mathbf{b})= \mathbf{x}^T\mathbf{w}+\mathbf{b}\]where \(\mathbf{x} \in \mathbb{R}^{N_{n-1}}\) is the input vector and \(\mathbf{y} \in \mathbb{R}\) is the output scalar. \(\mathbf{w} \in \mathbb{R}^{N_{n-1}}\) and \(\mathbf{b} \in \mathbb{R}\) are weights and bias, respectively, both of which are trainable if trainable[n] is True.
- Parameters
- descrpt
The descrptor \(\mathcal{D}\)
- neuron
Number of neurons \(N\) in each hidden layer of the fitting net
- resnet_dt
Time-step dt in the resnet construction: \(y = x + dt * \phi (Wx + b)\)
- numb_fparam
Number of frame parameter
- numb_aparam
Number of atomic parameter
- rcond
The condition number for the regression of atomic energy.
- tot_ener_zero
Force the total energy to zero. Useful for the charge fitting.
- trainable
If the weights of fitting net are trainable. Suppose that we have \(N_l\) hidden layers in the fitting net, this list is of length \(N_l + 1\), specifying if the hidden layers and the output layer are trainable.
- seed
Random seed for initializing the network parameters.
- atom_ener
Specifying atomic energy contribution in vacuum. The set_davg_zero key in the descrptor should be set.
- activation_function
The activation function \(\boldsymbol{\phi}\) in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- layer_name
list[Optional[str]],optional The name of the each layer. If two layers, either in the same fitting or different fittings, have the same name, they will share the same neural network parameters.
- use_aparam_as_mask: bool, optional
If True, the atomic parameters will be used as a mask that determines the atom is real/virtual. And the aparam will not be used as the atomic parameters for embedding.
- Attributes
precisionPrecision of fitting network.
Methods
build(inputs, natoms[, input_dict, reuse, ...])Build the computational graph for fitting net.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
compute_input_stats(all_stat[, protection])Compute the input statistics.
compute_output_stats(all_stat[, mixed_type])Compute the ouput statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the number of atomic parameters.
Get the number of frame parameters.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(inputs: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- inputs
The input descriptor
- input_dict
Additional dict for inputs. if numb_fparam > 0, should have input_dict[‘fparam’] if numb_aparam > 0, should have input_dict[‘aparam’]
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
enerThe system energy
- change_energy_bias(data, frozen_model, origin_type_map, full_type_map, bias_shift='delta', ntest=10) None[source]
Change the energy bias according to the input data and the pretrained model.
- Parameters
- data
DeepmdDataSystem The training data.
- frozen_model
str The path file of frozen model.
- origin_type_map
list The original type_map in dataset, they are targets to change the energy bias.
- full_type_map
str The full type_map in pretrained model
- bias_shift
str The mode for changing energy bias : [‘delta’, ‘statistic’] ‘delta’ : perform predictions on energies of target dataset,
and do least sqaure on the errors to obtain the target shift as bias.
‘statistic’ : directly use the statistic energy bias in the target dataset.
- ntest
int The number of test samples in a system to change the energy bias.
- data
- compute_input_stats(all_stat: dict, protection: float = 0.01) None[source]
Compute the input statistics.
- Parameters
- all_stat
if numb_fparam > 0 must have all_stat[‘fparam’] if numb_aparam > 0 must have all_stat[‘aparam’] can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
- compute_output_stats(all_stat: dict, mixed_type: bool = False) None[source]
Compute the ouput statistics.
- Parameters
- all_stat
must have the following components: all_stat[‘energy’] of shape n_sys x n_batch x n_frame can be prepared by model.make_stat_input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- class deepmd.fit.Fitting(*args, **kwargs)[source]
Bases:
PluginVariant- Attributes
precisionPrecision of fitting network.
Methods
get_loss(loss, lr)Get the loss function.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- abstract get_loss(loss: dict, lr) Loss[source]
Get the loss function.
- Parameters
- loss
dict the loss dict
- lr
LearningRateExp the learning rate
- loss
- Returns
Lossthe loss function
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the fitting net variables with the given dict.
- Parameters
Notes
This method is called by others when the fitting supported initialization from the given variables.
- property precision: DType
Precision of fitting network.
- class deepmd.fit.GlobalPolarFittingSeA(descrpt: Tensor, neuron: List[int] = [120, 120, 120], resnet_dt: bool = True, sel_type: Optional[List[int]] = None, fit_diag: bool = True, scale: Optional[List[float]] = None, diag_shift: Optional[List[float]] = None, seed: Optional[int] = None, activation_function: str = 'tanh', precision: str = 'default')[source]
Bases:
objectFit the system polarizability with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic polarizability prediction
- fit_diagbool
Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix.
- scale
List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i]
- diag_shift
List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- descrpt
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected atom types.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
- build(input_d, rot_mat, natoms, input_dict: Optional[dict] = None, reuse=None, suffix='') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
polarThe system polarizability
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- class deepmd.fit.PolarFittingSeA(*args, **kwargs)[source]
Bases:
FittingFit the atomic polarizability with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic polarizability prediction. If is None, all atoms are selected.
- fit_diagbool
Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix.
- scale
List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i]
- diag_shift
List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- descrpt
- Attributes
precisionPrecision of fitting network.
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
compute_input_stats(all_stat[, protection])Compute the input statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected atom types.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(input_d: Tensor, rot_mat: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '')[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
atomic_polarThe atomic polarizability
- compute_input_stats(all_stat, protection=0.01)[source]
Compute the input statistics.
- Parameters
- all_stat
Dictionary of inputs. can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
Submodules
deepmd.fit.dipole module
- class deepmd.fit.dipole.DipoleFittingSeA(*args, **kwargs)[source]
Bases:
FittingFit the atomic dipole with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic dipole prediction. If is None, all atoms are selected.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- descrpt
- Attributes
precisionPrecision of fitting network.
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected type.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(input_d: Tensor, rot_mat: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
dipoleThe atomic dipole.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
deepmd.fit.dos module
- class deepmd.fit.dos.DOSFitting(*args, **kwargs)[source]
Bases:
FittingFitting the density of states (DOS) of the system. The energy should be shifted by the fermi level.
- Parameters
- descrpt
The descrptor \(\mathcal{D}\)
- neuron
Number of neurons \(N\) in each hidden layer of the fitting net
- resnet_dt
Time-step dt in the resnet construction: \(y = x + dt * \phi (Wx + b)\)
- numb_fparam
Number of frame parameter
- numb_aparam
Number of atomic parameter
- ! numb_dos (added)
Number of gridpoints on which the DOS is evaluated (NEDOS in VASP)
- rcond
The condition number for the regression of atomic energy.
- trainable
If the weights of fitting net are trainable. Suppose that we have \(N_l\) hidden layers in the fitting net, this list is of length \(N_l + 1\), specifying if the hidden layers and the output layer are trainable.
- seed
Random seed for initializing the network parameters.
- activation_function
The activation function \(\boldsymbol{\phi}\) in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- layer_name
list[Optional[str]],optional The name of the each layer. If two layers, either in the same fitting or different fittings, have the same name, they will share the same neural network parameters.
- use_aparam_as_mask: bool, optional
If True, the atomic parameters will be used as a mask that determines the atom is real/virtual. And the aparam will not be used as the atomic parameters for embedding.
- Attributes
precisionPrecision of fitting network.
Methods
build(inputs, natoms[, input_dict, reuse, ...])Build the computational graph for fitting net.
compute_input_stats(all_stat[, protection])Compute the input statistics.
compute_output_stats(all_stat[, mixed_type])Compute the ouput statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(inputs: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- inputs
The input descriptor
- input_dict
Additional dict for inputs. if numb_fparam > 0, should have input_dict[‘fparam’] if numb_aparam > 0, should have input_dict[‘aparam’]
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
enerThe system energy
- compute_input_stats(all_stat: dict, protection: float = 0.01) None[source]
Compute the input statistics.
- Parameters
- all_stat
if numb_fparam > 0 must have all_stat[‘fparam’] if numb_aparam > 0 must have all_stat[‘aparam’] can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
- compute_output_stats(all_stat: dict, mixed_type: bool = False) None[source]
Compute the ouput statistics.
- Parameters
- all_stat
must have the following components: all_stat[‘dos’] of shape n_sys x n_batch x n_frame x numb_dos can be prepared by model.make_stat_input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
deepmd.fit.ener module
- class deepmd.fit.ener.EnerFitting(*args, **kwargs)[source]
Bases:
FittingFitting the energy of the system. The force and the virial can also be trained.
The potential energy \(E\) is a fitting network function of the descriptor \(\mathcal{D}\):
\[E(\mathcal{D}) = \mathcal{L}^{(n)} \circ \mathcal{L}^{(n-1)} \circ \cdots \circ \mathcal{L}^{(1)} \circ \mathcal{L}^{(0)}\]The first \(n\) hidden layers \(\mathcal{L}^{(0)}, \cdots, \mathcal{L}^{(n-1)}\) are given by
\[\mathbf{y}=\mathcal{L}(\mathbf{x};\mathbf{w},\mathbf{b})= \boldsymbol{\phi}(\mathbf{x}^T\mathbf{w}+\mathbf{b})\]where \(\mathbf{x} \in \mathbb{R}^{N_1}\) is the input vector and \(\mathbf{y} \in \mathbb{R}^{N_2}\) is the output vector. \(\mathbf{w} \in \mathbb{R}^{N_1 \times N_2}\) and \(\mathbf{b} \in \mathbb{R}^{N_2}\) are weights and biases, respectively, both of which are trainable if trainable[i] is True. \(\boldsymbol{\phi}\) is the activation function.
The output layer \(\mathcal{L}^{(n)}\) is given by
\[\mathbf{y}=\mathcal{L}^{(n)}(\mathbf{x};\mathbf{w},\mathbf{b})= \mathbf{x}^T\mathbf{w}+\mathbf{b}\]where \(\mathbf{x} \in \mathbb{R}^{N_{n-1}}\) is the input vector and \(\mathbf{y} \in \mathbb{R}\) is the output scalar. \(\mathbf{w} \in \mathbb{R}^{N_{n-1}}\) and \(\mathbf{b} \in \mathbb{R}\) are weights and bias, respectively, both of which are trainable if trainable[n] is True.
- Parameters
- descrpt
The descrptor \(\mathcal{D}\)
- neuron
Number of neurons \(N\) in each hidden layer of the fitting net
- resnet_dt
Time-step dt in the resnet construction: \(y = x + dt * \phi (Wx + b)\)
- numb_fparam
Number of frame parameter
- numb_aparam
Number of atomic parameter
- rcond
The condition number for the regression of atomic energy.
- tot_ener_zero
Force the total energy to zero. Useful for the charge fitting.
- trainable
If the weights of fitting net are trainable. Suppose that we have \(N_l\) hidden layers in the fitting net, this list is of length \(N_l + 1\), specifying if the hidden layers and the output layer are trainable.
- seed
Random seed for initializing the network parameters.
- atom_ener
Specifying atomic energy contribution in vacuum. The set_davg_zero key in the descrptor should be set.
- activation_function
The activation function \(\boldsymbol{\phi}\) in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- layer_name
list[Optional[str]],optional The name of the each layer. If two layers, either in the same fitting or different fittings, have the same name, they will share the same neural network parameters.
- use_aparam_as_mask: bool, optional
If True, the atomic parameters will be used as a mask that determines the atom is real/virtual. And the aparam will not be used as the atomic parameters for embedding.
- Attributes
precisionPrecision of fitting network.
Methods
build(inputs, natoms[, input_dict, reuse, ...])Build the computational graph for fitting net.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
compute_input_stats(all_stat[, protection])Compute the input statistics.
compute_output_stats(all_stat[, mixed_type])Compute the ouput statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the number of atomic parameters.
Get the number of frame parameters.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(inputs: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- inputs
The input descriptor
- input_dict
Additional dict for inputs. if numb_fparam > 0, should have input_dict[‘fparam’] if numb_aparam > 0, should have input_dict[‘aparam’]
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
enerThe system energy
- change_energy_bias(data, frozen_model, origin_type_map, full_type_map, bias_shift='delta', ntest=10) None[source]
Change the energy bias according to the input data and the pretrained model.
- Parameters
- data
DeepmdDataSystem The training data.
- frozen_model
str The path file of frozen model.
- origin_type_map
list The original type_map in dataset, they are targets to change the energy bias.
- full_type_map
str The full type_map in pretrained model
- bias_shift
str The mode for changing energy bias : [‘delta’, ‘statistic’] ‘delta’ : perform predictions on energies of target dataset,
and do least sqaure on the errors to obtain the target shift as bias.
‘statistic’ : directly use the statistic energy bias in the target dataset.
- ntest
int The number of test samples in a system to change the energy bias.
- data
- compute_input_stats(all_stat: dict, protection: float = 0.01) None[source]
Compute the input statistics.
- Parameters
- all_stat
if numb_fparam > 0 must have all_stat[‘fparam’] if numb_aparam > 0 must have all_stat[‘aparam’] can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
- compute_output_stats(all_stat: dict, mixed_type: bool = False) None[source]
Compute the ouput statistics.
- Parameters
- all_stat
must have the following components: all_stat[‘energy’] of shape n_sys x n_batch x n_frame can be prepared by model.make_stat_input
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
deepmd.fit.fitting module
- class deepmd.fit.fitting.Fitting(*args, **kwargs)[source]
Bases:
PluginVariant- Attributes
precisionPrecision of fitting network.
Methods
get_loss(loss, lr)Get the loss function.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- abstract get_loss(loss: dict, lr) Loss[source]
Get the loss function.
- Parameters
- loss
dict the loss dict
- lr
LearningRateExp the learning rate
- loss
- Returns
Lossthe loss function
- init_variables(graph: Graph, graph_def: GraphDef, suffix: str = '') None[source]
Init the fitting net variables with the given dict.
- Parameters
Notes
This method is called by others when the fitting supported initialization from the given variables.
- property precision: DType
Precision of fitting network.
deepmd.fit.polar module
- class deepmd.fit.polar.GlobalPolarFittingSeA(descrpt: Tensor, neuron: List[int] = [120, 120, 120], resnet_dt: bool = True, sel_type: Optional[List[int]] = None, fit_diag: bool = True, scale: Optional[List[float]] = None, diag_shift: Optional[List[float]] = None, seed: Optional[int] = None, activation_function: str = 'tanh', precision: str = 'default')[source]
Bases:
objectFit the system polarizability with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic polarizability prediction
- fit_diagbool
Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix.
- scale
List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i]
- diag_shift
List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- descrpt
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected atom types.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
- build(input_d, rot_mat, natoms, input_dict: Optional[dict] = None, reuse=None, suffix='') Tensor[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
polarThe system polarizability
- enable_mixed_precision(mixed_prec: Optional[dict] = None) None[source]
Reveive the mixed precision setting.
- Parameters
- mixed_prec
The mixed precision setting used in the embedding net
- class deepmd.fit.polar.PolarFittingSeA(*args, **kwargs)[source]
Bases:
FittingFit the atomic polarizability with descriptor se_a.
- Parameters
- descrpt
tf.Tensor The descrptor
- neuron
List[int] Number of neurons in each hidden layer of the fitting net
- resnet_dtbool
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- sel_type
List[int] The atom types selected to have an atomic polarizability prediction. If is None, all atoms are selected.
- fit_diagbool
Fit the diagonal part of the rotational invariant polarizability matrix, which will be converted to normal polarizability matrix by contracting with the rotation matrix.
- scale
List[float] The output of the fitting net (polarizability matrix) for type i atom will be scaled by scale[i]
- diag_shift
List[float] The diagonal part of the polarizability matrix of type i will be shifted by diag_shift[i]. The shift operation is carried out after scale.
- seed
int Random seed for initializing the network parameters.
- activation_function
str The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
str The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- descrpt
- Attributes
precisionPrecision of fitting network.
Methods
build(input_d, rot_mat, natoms[, ...])Build the computational graph for fitting net.
compute_input_stats(all_stat[, protection])Compute the input statistics.
enable_mixed_precision([mixed_prec])Reveive the mixed precision setting.
get_loss(loss, lr)Get the loss function.
Get the output size.
Get selected atom types.
init_variables(graph, graph_def[, suffix])Init the fitting net variables with the given dict.
register(key)Register a Fitting plugin.
- build(input_d: Tensor, rot_mat: Tensor, natoms: Tensor, input_dict: Optional[dict] = None, reuse: Optional[bool] = None, suffix: str = '')[source]
Build the computational graph for fitting net.
- Parameters
- input_d
The input descriptor
- rot_mat
The rotation matrix from the descriptor.
- natoms
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- input_dict
Additional dict for inputs.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
atomic_polarThe atomic polarizability
- compute_input_stats(all_stat, protection=0.01)[source]
Compute the input statistics.
- Parameters
- all_stat
Dictionary of inputs. can be prepared by model.make_stat_input
- protection
Divided-by-zero protection
deepmd.infer package
Submodule containing all the implemented potentials.
- class deepmd.infer.DeepDOS(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = True, input_map: Optional[dict] = None)[source]
Bases:
DeepEvalConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:True If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the dos, atom_dos by using this model.
eval_descriptor(coords, cells, atom_types[, ...])Evaluate descriptors by using this DP.
eval_typeebd()Evaluate output of type embedding network by using this model.
Get the number (dimension) of atomic parameters of this DP.
Get the number (dimension) of frame parameters of this DP.
Get the number of atom types of this model.
Get the length of DOS output of this DP model.
get_rcut()Get the cut-off radius of this model.
Unsupported in this model.
Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, mixed_type: bool = False) Tuple[ndarray, ...][source]
Evaluate the dos, atom_dos by using this model.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Calculate the atomic energy and virial
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
dosThe electron density of state.
atom_dosThe atom-sited density of state. Only returned when atomic == True
- eval_descriptor(coords: ndarray, cells: ndarray, atom_types: List[int], fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) array[source]
Evaluate descriptors by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
descriptorDescriptors.
- class deepmd.infer.DeepDipole(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- class deepmd.infer.DeepEval(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
objectCommon methods for DeepPot, DeepWFC, DeepPolar, …
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:False If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList,optional The ASE neighbor list class to produce the neighbor list. If None, the neighbor list will be built natively in the model.
- model_file
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
Evaluate output of type embedding network by using this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- build_neighbor_list(coords: ndarray, cell: Optional[ndarray], atype: ndarray, imap: ndarray, neighbor_list)[source]
Make the mesh with neighbor list for a single frame.
- Parameters
- coords
np.ndarray The coordinates of atoms. Should be of shape [natoms, 3]
- cell
Optional[np.ndarray] The cell of the system. Should be of shape [3, 3]
- atype
np.ndarray The type of atoms. Should be of shape [natoms]
- imap
np.ndarray The index map of atoms. Should be of shape [natoms]
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList ASE neighbor list. The following method or attribute will be used/set: bothways, self_interaction, update, build, first_neigh, pair_second, offset_vec.
- coords
- Returns
- natoms_vec
np.ndarray The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: nloc natoms[1]: nall natoms[i]: 2 <= i < Ntypes+2, number of type i atoms for nloc
- coords
np.ndarray The coordinates of atoms, including ghost atoms. Should be of shape [nframes, nall, 3]
- atype
np.ndarray The type of atoms, including ghost atoms. Should be of shape [nall]
- mesh
np.ndarray The mesh in nei_mode=4.
- imap
np.ndarray The index map of atoms. Should be of shape [nall]
- ghost_map
np.ndarray The index map of ghost atoms. Should be of shape [nghost]
- natoms_vec
- eval_typeebd() ndarray[source]
Evaluate output of type embedding network by using this model.
- Returns
np.ndarrayThe output of type embedding network. The shape is [ntypes, o_size], where ntypes is the number of types, and o_size is the number of nodes in the output layer.
- Raises
KeyErrorIf the model does not enable type embedding.
See also
deepmd.utils.type_embed.TypeEmbedNetThe type embedding network.
Examples
Get the output of type embedding network of graph.pb:
>>> from deepmd.infer import DeepPotential >>> dp = DeepPotential('graph.pb') >>> dp.eval_typeebd()
- make_natoms_vec(atom_types: ndarray, mixed_type: bool = False) ndarray[source]
Make the natom vector used by deepmd-kit.
- Parameters
- atom_types
The type of atoms
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
natomsThe number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- static reverse_map(vec: ndarray, imap: List[int]) ndarray[source]
Reverse mapping of a vector according to the index map.
- Parameters
- vec
Input vector. Be of shape [nframes, natoms, -1]
- imap
Index map. Be of shape [natoms]
- Returns
vec_outReverse mapped vector.
- property sess: Session
Get TF session.
- static sort_input(coord: ndarray, atom_type: ndarray, sel_atoms: Optional[List[int]] = None, mixed_type: bool = False)[source]
Sort atoms in the system according their types.
- Parameters
- coord
The coordinates of atoms. Should be of shape [nframes, natoms, 3]
- atom_type
The type of atoms Should be of shape [natoms]
- sel_atoms
The selected atoms by type
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
coord_outThe coordinates after sorting
atom_type_outThe atom types after sorting
idx_mapThe index mapping from the input to the output. For example coord_out = coord[:,idx_map,:]
sel_atom_typeOnly output if sel_atoms is not None The sorted selected atom types
sel_idx_mapOnly output if sel_atoms is not None The index mapping from the selected atoms to sorted selected atoms.
- class deepmd.infer.DeepGlobalPolar(model_file: str, load_prefix: str = 'load', default_tf_graph: bool = False, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
str The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None) ndarray[source]
Evaluate the model.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Not used in this model
- fparam
Not used in this model
- aparam
Not used in this model
- efield
Not used in this model
- Returns
tensorThe returned tensor If atomic == False then of size nframes x variable_dof else of size nframes x natoms x variable_dof
- class deepmd.infer.DeepPolar(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- class deepmd.infer.DeepPot(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = True, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepEvalConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:True If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList,optional The ASE neighbor list class to produce the neighbor list. If None, the neighbor list will be built natively in the model.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
Examples
>>> from deepmd.infer import DeepPot >>> import numpy as np >>> dp = DeepPot('graph.pb') >>> coord = np.array([[1,0,0], [0,0,1.5], [1,0,3]]).reshape([1, -1]) >>> cell = np.diag(10 * np.ones(3)).reshape([1, -1]) >>> atype = [1,0,1] >>> e, f, v = dp.eval(coord, cell, atype)
where e, f and v are predicted energy, force and virial of the system, respectively.
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the energy, force and virial by using this DP.
eval_descriptor(coords, cells, atom_types[, ...])Evaluate descriptors by using this DP.
eval_typeebd()Evaluate output of type embedding network by using this model.
Get the descriptor type of this model.
Get the number (dimension) of atomic parameters of this DP.
Get the number (dimension) of frame parameters of this DP.
Get the number of atom types of this model.
Get the number of spin atom types of this model.
get_rcut()Get the cut-off radius of this model.
Unsupported in this model.
Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) Tuple[ndarray, ...][source]
Evaluate the energy, force and virial by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Calculate the atomic energy and virial
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
energyThe system energy.
forceThe force on each atom
virialThe virial
atom_energyThe atomic energy. Only returned when atomic == True
atom_virialThe atomic virial. Only returned when atomic == True
- eval_descriptor(coords: ndarray, cells: ndarray, atom_types: List[int], fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) array[source]
Evaluate descriptors by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
descriptorDescriptors.
- deepmd.infer.DeepPotential(model_file: Union[str, Path], load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None) Union[DeepDipole, DeepGlobalPolar, DeepPolar, DeepPot, DeepDOS, DeepWFC][source]
Factory function that will inialize appropriate potential read from model_file.
- Parameters
- model_file
str The name of the frozen model file.
- load_prefix
str The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
- Returns
Union[DeepDipole,DeepGlobalPolar,DeepPolar,DeepPot,DeepWFC]one of the available potentials
- Raises
RuntimeErrorif model file does not correspond to any implementd potential
- class deepmd.infer.DeepWFC(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None)[source]
Bases:
DeepTensorConstructor.
- Parameters
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- class deepmd.infer.DipoleChargeModifier(model_name: str, model_charge_map: List[float], sys_charge_map: List[float], ewald_h: float = 1, ewald_beta: float = 1)[source]
Bases:
DeepDipole- Parameters
- model_name
The model file for the DeepDipole model
- model_charge_map
Gives the amount of charge for the wfcc
- sys_charge_map
Gives the amount of charge for the real atoms
- ewald_h
Grid spacing of the reciprocal part of Ewald sum. Unit: A
- ewald_beta
Splitting parameter of the Ewald sum. Unit: A^{-1}
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
Build the computational graph for the force and virial inference.
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coord, box, atype[, eval_fv])Evaluate the modification.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
get_dim_aparam()Unsupported in this model.
get_dim_fparam()Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
modify_data(data, data_sys)Modify data.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coord: ndarray, box: ndarray, atype: ndarray, eval_fv: bool = True) Tuple[ndarray, ndarray, ndarray][source]
Evaluate the modification.
- Parameters
- coord
The coordinates of atoms
- box
The simulation region. PBC is assumed
- atype
The atom types
- eval_fv
Evaluate force and virial
- Returns
tot_eThe energy modification
tot_fThe force modification
tot_vThe virial modification
- modify_data(data: dict, data_sys: DeepmdData) None[source]
Modify data.
- Parameters
- data
Internal data of DeepmdData. Be a dict, has the following keys - coord coordinates - box simulation box - type atom types - find_energy tells if data has energy - find_force tells if data has force - find_virial tells if data has virial - energy energy - force force - virial virial
- data_sys
DeepmdData The data system.
- class deepmd.infer.EwaldRecp(hh, beta)[source]
Bases:
objectEvaluate the reciprocal part of the Ewald sum.
Methods
eval(coord, charge, box)Evaluate.
- deepmd.infer.calc_model_devi(coord, box, atype, models, fname=None, frequency=1, mixed_type=False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, real_data: Optional[dict] = None, atomic: bool = False, relative: Optional[float] = None, relative_v: Optional[float] = None)[source]
Python interface to calculate model deviation.
- Parameters
- coord
numpy.ndarray, n_frames x n_atoms x 3 Coordinates of system to calculate
- box
numpy.ndarrayorNone, n_frames x 3 x 3 Box to specify periodic boundary condition. If None, no pbc will be used
- atype
numpy.ndarray, n_atoms x 1 Atom types
- models
listofDeepPotmodels Models used to evaluate deviation
- fname
strorNone File to dump results, default None
- frequency
int Steps between frames (if the system is given by molecular dynamics engine), default 1
- mixed_typebool
Whether the input atype is in mixed_type format or not
- fparam
numpy.ndarray frame specific parameters
- aparam
numpy.ndarray atomic specific parameters
- real_data
dict,optional real data to calculate RMS real error
- atomicbool, default:
False If True, calculate the force model deviation of each atom.
- relative
float, default:None If given, calculate the relative model deviation of force. The value is the level parameter for computing the relative model deviation of the force.
- relative_v
float, default:None If given, calculate the relative model deviation of virial. The value is the level parameter for computing the relative model deviation of the virial.
- coord
- Returns
- model_devi
numpy.ndarray, n_frames x 8 Model deviation results. The first column is index of steps, the other 7 columns are max_devi_v, min_devi_v, avg_devi_v, max_devi_f, min_devi_f, avg_devi_f, devi_e.
- model_devi
Examples
>>> from deepmd.infer import calc_model_devi >>> from deepmd.infer import DeepPot as DP >>> import numpy as np >>> coord = np.array([[1,0,0], [0,0,1.5], [1,0,3]]).reshape([1, -1]) >>> cell = np.diag(10 * np.ones(3)).reshape([1, -1]) >>> atype = [1,0,1] >>> graphs = [DP("graph.000.pb"), DP("graph.001.pb")] >>> model_devi = calc_model_devi(coord, cell, atype, graphs)
Submodules
deepmd.infer.data_modifier module
- class deepmd.infer.data_modifier.DipoleChargeModifier(model_name: str, model_charge_map: List[float], sys_charge_map: List[float], ewald_h: float = 1, ewald_beta: float = 1)[source]
Bases:
DeepDipole- Parameters
- model_name
The model file for the DeepDipole model
- model_charge_map
Gives the amount of charge for the wfcc
- sys_charge_map
Gives the amount of charge for the real atoms
- ewald_h
Grid spacing of the reciprocal part of Ewald sum. Unit: A
- ewald_beta
Splitting parameter of the Ewald sum. Unit: A^{-1}
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
Build the computational graph for the force and virial inference.
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coord, box, atype[, eval_fv])Evaluate the modification.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
get_dim_aparam()Unsupported in this model.
get_dim_fparam()Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
modify_data(data, data_sys)Modify data.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coord: ndarray, box: ndarray, atype: ndarray, eval_fv: bool = True) Tuple[ndarray, ndarray, ndarray][source]
Evaluate the modification.
- Parameters
- coord
The coordinates of atoms
- box
The simulation region. PBC is assumed
- atype
The atom types
- eval_fv
Evaluate force and virial
- Returns
tot_eThe energy modification
tot_fThe force modification
tot_vThe virial modification
- modify_data(data: dict, data_sys: DeepmdData) None[source]
Modify data.
- Parameters
- data
Internal data of DeepmdData. Be a dict, has the following keys - coord coordinates - box simulation box - type atom types - find_energy tells if data has energy - find_force tells if data has force - find_virial tells if data has virial - energy energy - force force - virial virial
- data_sys
DeepmdData The data system.
deepmd.infer.deep_dipole module
- class deepmd.infer.deep_dipole.DeepDipole(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
deepmd.infer.deep_dos module
- class deepmd.infer.deep_dos.DeepDOS(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = True, input_map: Optional[dict] = None)[source]
Bases:
DeepEvalConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:True If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the dos, atom_dos by using this model.
eval_descriptor(coords, cells, atom_types[, ...])Evaluate descriptors by using this DP.
eval_typeebd()Evaluate output of type embedding network by using this model.
Get the number (dimension) of atomic parameters of this DP.
Get the number (dimension) of frame parameters of this DP.
Get the number of atom types of this model.
Get the length of DOS output of this DP model.
get_rcut()Get the cut-off radius of this model.
Unsupported in this model.
Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, mixed_type: bool = False) Tuple[ndarray, ...][source]
Evaluate the dos, atom_dos by using this model.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Calculate the atomic energy and virial
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
dosThe electron density of state.
atom_dosThe atom-sited density of state. Only returned when atomic == True
- eval_descriptor(coords: ndarray, cells: ndarray, atom_types: List[int], fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) array[source]
Evaluate descriptors by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
descriptorDescriptors.
deepmd.infer.deep_eval module
- class deepmd.infer.deep_eval.DeepEval(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
objectCommon methods for DeepPot, DeepWFC, DeepPolar, …
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:False If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList,optional The ASE neighbor list class to produce the neighbor list. If None, the neighbor list will be built natively in the model.
- model_file
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
Evaluate output of type embedding network by using this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- build_neighbor_list(coords: ndarray, cell: Optional[ndarray], atype: ndarray, imap: ndarray, neighbor_list)[source]
Make the mesh with neighbor list for a single frame.
- Parameters
- coords
np.ndarray The coordinates of atoms. Should be of shape [natoms, 3]
- cell
Optional[np.ndarray] The cell of the system. Should be of shape [3, 3]
- atype
np.ndarray The type of atoms. Should be of shape [natoms]
- imap
np.ndarray The index map of atoms. Should be of shape [natoms]
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList ASE neighbor list. The following method or attribute will be used/set: bothways, self_interaction, update, build, first_neigh, pair_second, offset_vec.
- coords
- Returns
- natoms_vec
np.ndarray The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: nloc natoms[1]: nall natoms[i]: 2 <= i < Ntypes+2, number of type i atoms for nloc
- coords
np.ndarray The coordinates of atoms, including ghost atoms. Should be of shape [nframes, nall, 3]
- atype
np.ndarray The type of atoms, including ghost atoms. Should be of shape [nall]
- mesh
np.ndarray The mesh in nei_mode=4.
- imap
np.ndarray The index map of atoms. Should be of shape [nall]
- ghost_map
np.ndarray The index map of ghost atoms. Should be of shape [nghost]
- natoms_vec
- eval_typeebd() ndarray[source]
Evaluate output of type embedding network by using this model.
- Returns
np.ndarrayThe output of type embedding network. The shape is [ntypes, o_size], where ntypes is the number of types, and o_size is the number of nodes in the output layer.
- Raises
KeyErrorIf the model does not enable type embedding.
See also
deepmd.utils.type_embed.TypeEmbedNetThe type embedding network.
Examples
Get the output of type embedding network of graph.pb:
>>> from deepmd.infer import DeepPotential >>> dp = DeepPotential('graph.pb') >>> dp.eval_typeebd()
- make_natoms_vec(atom_types: ndarray, mixed_type: bool = False) ndarray[source]
Make the natom vector used by deepmd-kit.
- Parameters
- atom_types
The type of atoms
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
natomsThe number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- static reverse_map(vec: ndarray, imap: List[int]) ndarray[source]
Reverse mapping of a vector according to the index map.
- Parameters
- vec
Input vector. Be of shape [nframes, natoms, -1]
- imap
Index map. Be of shape [natoms]
- Returns
vec_outReverse mapped vector.
- property sess: Session
Get TF session.
- static sort_input(coord: ndarray, atom_type: ndarray, sel_atoms: Optional[List[int]] = None, mixed_type: bool = False)[source]
Sort atoms in the system according their types.
- Parameters
- coord
The coordinates of atoms. Should be of shape [nframes, natoms, 3]
- atom_type
The type of atoms Should be of shape [natoms]
- sel_atoms
The selected atoms by type
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
coord_outThe coordinates after sorting
atom_type_outThe atom types after sorting
idx_mapThe index mapping from the input to the output. For example coord_out = coord[:,idx_map,:]
sel_atom_typeOnly output if sel_atoms is not None The sorted selected atom types
sel_idx_mapOnly output if sel_atoms is not None The index mapping from the selected atoms to sorted selected atoms.
deepmd.infer.deep_polar module
- class deepmd.infer.deep_polar.DeepGlobalPolar(model_file: str, load_prefix: str = 'load', default_tf_graph: bool = False, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
str The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None) ndarray[source]
Evaluate the model.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Not used in this model
- fparam
Not used in this model
- aparam
Not used in this model
- efield
Not used in this model
- Returns
tensorThe returned tensor If atomic == False then of size nframes x variable_dof else of size nframes x natoms x variable_dof
- class deepmd.infer.deep_polar.DeepPolar(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepTensorConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
deepmd.infer.deep_pot module
- class deepmd.infer.deep_pot.DeepPot(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, auto_batch_size: Union[bool, int, AutoBatchSize] = True, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepEvalConstructor.
- Parameters
- model_file
Path The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- auto_batch_sizebool or
intorAutomaticBatchSize, default:True If True, automatic batch size will be used. If int, it will be used as the initial batch size.
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NewPrimitiveNeighborList,optional The ASE neighbor list class to produce the neighbor list. If None, the neighbor list will be built natively in the model.
- model_file
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
Examples
>>> from deepmd.infer import DeepPot >>> import numpy as np >>> dp = DeepPot('graph.pb') >>> coord = np.array([[1,0,0], [0,0,1.5], [1,0,3]]).reshape([1, -1]) >>> cell = np.diag(10 * np.ones(3)).reshape([1, -1]) >>> atype = [1,0,1] >>> e, f, v = dp.eval(coord, cell, atype)
where e, f and v are predicted energy, force and virial of the system, respectively.
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the energy, force and virial by using this DP.
eval_descriptor(coords, cells, atom_types[, ...])Evaluate descriptors by using this DP.
eval_typeebd()Evaluate output of type embedding network by using this model.
Get the descriptor type of this model.
Get the number (dimension) of atomic parameters of this DP.
Get the number (dimension) of frame parameters of this DP.
Get the number of atom types of this model.
Get the number of spin atom types of this model.
get_rcut()Get the cut-off radius of this model.
Unsupported in this model.
Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) Tuple[ndarray, ...][source]
Evaluate the energy, force and virial by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Calculate the atomic energy and virial
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
energyThe system energy.
forceThe force on each atom
virialThe virial
atom_energyThe atomic energy. Only returned when atomic == True
atom_virialThe atomic virial. Only returned when atomic == True
- eval_descriptor(coords: ndarray, cells: ndarray, atom_types: List[int], fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) array[source]
Evaluate descriptors by using this DP.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- fparam
The frame parameter. The array can be of size : - nframes x dim_fparam. - dim_fparam. Then all frames are assumed to be provided with the same fparam.
- aparam
The atomic parameter The array can be of size : - nframes x natoms x dim_aparam. - natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. - dim_aparam. Then all frames and atoms are provided with the same aparam.
- efield
The external field on atoms. The array should be of size nframes x natoms x 3
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
descriptorDescriptors.
deepmd.infer.deep_tensor module
- class deepmd.infer.deep_tensor.DeepTensor(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None, neighbor_list=None)[source]
Bases:
DeepEvalEvaluates a tensor model.
- Parameters
- model_file: str
The name of the frozen model file.
- load_prefix: str
The prefix in the load computational graph
- default_tf_graphbool
If uses the default tf graph, otherwise build a new tf graph for evaluation
- input_map
dict,optional The input map for tf.import_graph_def. Only work with default tf graph
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Get the number (dimension) of atomic parameters of this DP.
Get the number (dimension) of frame parameters of this DP.
Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
Get the selected atom types of this model.
Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
- eval(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = True, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, efield: Optional[ndarray] = None, mixed_type: bool = False) ndarray[source]
Evaluate the model.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
If True (default), return the atomic tensor Otherwise return the global tensor
- fparam
Not used in this model
- aparam
Not used in this model
- efield
Not used in this model
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
tensorThe returned tensor If atomic == False then of size nframes x output_dim else of size nframes x natoms x output_dim
- eval_full(coords: ndarray, cells: ndarray, atom_types: List[int], atomic: bool = False, fparam: Optional[array] = None, aparam: Optional[array] = None, efield: Optional[array] = None, mixed_type: bool = False) Tuple[ndarray, ...][source]
Evaluate the model with interface similar to the energy model. Will return global tensor, component-wise force and virial and optionally atomic tensor and atomic virial.
- Parameters
- coords
The coordinates of atoms. The array should be of size nframes x natoms x 3
- cells
The cell of the region. If None then non-PBC is assumed, otherwise using PBC. The array should be of size nframes x 9
- atom_types
The atom types The list should contain natoms ints
- atomic
Whether to calculate atomic tensor and virial
- fparam
Not used in this model
- aparam
Not used in this model
- efield
Not used in this model
- mixed_type
Whether to perform the mixed_type mode. If True, the input data has the mixed_type format (see doc/model/train_se_atten.md), in which frames in a system may have different natoms_vec(s), with the same nloc.
- Returns
tensorThe global tensor. shape: [nframes x nout]
forceThe component-wise force (negative derivative) on each atom. shape: [nframes x nout x natoms x 3]
virialThe component-wise virial of the tensor. shape: [nframes x nout x 9]
atom_tensorThe atomic tensor. Only returned when atomic == True shape: [nframes x natoms x nout]
atom_virialThe atomic virial. Only returned when atomic == True shape: [nframes x nout x natoms x 9]
- tensors: ClassVar[Dict[str, str]] = {'t_box': 't_box:0', 't_coord': 't_coord:0', 't_mesh': 't_mesh:0', 't_natoms': 't_natoms:0', 't_ntypes': 'descrpt_attr/ntypes:0', 't_ouput_dim': 'model_attr/output_dim:0', 't_rcut': 'descrpt_attr/rcut:0', 't_sel_type': 'model_attr/sel_type:0', 't_tmap': 'model_attr/tmap:0', 't_type': 't_type:0'}
deepmd.infer.deep_wfc module
- class deepmd.infer.deep_wfc.DeepWFC(model_file: Path, load_prefix: str = 'load', default_tf_graph: bool = False, input_map: Optional[dict] = None)[source]
Bases:
DeepTensorConstructor.
- Parameters
Warning
For developers: DeepTensor initializer must be called at the end after self.tensors are modified because it uses the data in self.tensors dict. Do not chanage the order!
- Attributes
model_typeGet type of model.
model_versionGet version of model.
sessGet TF session.
Methods
build_neighbor_list(coords, cell, atype, ...)Make the mesh with neighbor list for a single frame.
eval(coords, cells, atom_types[, atomic, ...])Evaluate the model.
eval_full(coords, cells, atom_types[, ...])Evaluate the model with interface similar to the energy model.
eval_typeebd()Evaluate output of type embedding network by using this model.
Unsupported in this model.
Unsupported in this model.
get_ntypes()Get the number of atom types of this model.
get_rcut()Get the cut-off radius of this model.
get_sel_type()Get the selected atom types of this model.
get_type_map()Get the type map (element name of the atom types) of this model.
make_natoms_vec(atom_types[, mixed_type])Make the natom vector used by deepmd-kit.
reverse_map(vec, imap)Reverse mapping of a vector according to the index map.
sort_input(coord, atom_type[, sel_atoms, ...])Sort atoms in the system according their types.
deepmd.infer.ewald_recp module
deepmd.infer.model_devi module
- deepmd.infer.model_devi.calc_model_devi(coord, box, atype, models, fname=None, frequency=1, mixed_type=False, fparam: Optional[ndarray] = None, aparam: Optional[ndarray] = None, real_data: Optional[dict] = None, atomic: bool = False, relative: Optional[float] = None, relative_v: Optional[float] = None)[source]
Python interface to calculate model deviation.
- Parameters
- coord
numpy.ndarray, n_frames x n_atoms x 3 Coordinates of system to calculate
- box
numpy.ndarrayorNone, n_frames x 3 x 3 Box to specify periodic boundary condition. If None, no pbc will be used
- atype
numpy.ndarray, n_atoms x 1 Atom types
- models
listofDeepPotmodels Models used to evaluate deviation
- fname
strorNone File to dump results, default None
- frequency
int Steps between frames (if the system is given by molecular dynamics engine), default 1
- mixed_typebool
Whether the input atype is in mixed_type format or not
- fparam
numpy.ndarray frame specific parameters
- aparam
numpy.ndarray atomic specific parameters
- real_data
dict,optional real data to calculate RMS real error
- atomicbool, default:
False If True, calculate the force model deviation of each atom.
- relative
float, default:None If given, calculate the relative model deviation of force. The value is the level parameter for computing the relative model deviation of the force.
- relative_v
float, default:None If given, calculate the relative model deviation of virial. The value is the level parameter for computing the relative model deviation of the virial.
- coord
- Returns
- model_devi
numpy.ndarray, n_frames x 8 Model deviation results. The first column is index of steps, the other 7 columns are max_devi_v, min_devi_v, avg_devi_v, max_devi_f, min_devi_f, avg_devi_f, devi_e.
- model_devi
Examples
>>> from deepmd.infer import calc_model_devi >>> from deepmd.infer import DeepPot as DP >>> import numpy as np >>> coord = np.array([[1,0,0], [0,0,1.5], [1,0,3]]).reshape([1, -1]) >>> cell = np.diag(10 * np.ones(3)).reshape([1, -1]) >>> atype = [1,0,1] >>> graphs = [DP("graph.000.pb"), DP("graph.001.pb")] >>> model_devi = calc_model_devi(coord, cell, atype, graphs)
- deepmd.infer.model_devi.calc_model_devi_e(es: ndarray, real_e: Optional[ndarray] = None) ndarray[source]
Calculate model deviation of total energy per atom.
Here we don’t use the atomic energy, as the decomposition of energy is arbitrary and not unique. There is no fitting target for atomic energy.
- Parameters
- es
numpy.ndarray size of `n_models x n_frames x 1
- real_e
numpy.ndarray real energy, size of n_frames x 1. If given, the RMS real error is calculated instead.
- es
- Returns
- max_devi_e
numpy.ndarray maximum deviation of energy
- max_devi_e
- deepmd.infer.model_devi.calc_model_devi_f(fs: ndarray, real_f: Optional[ndarray] = None, relative: Optional[float] = None, atomic: Literal[False] = False) Tuple[ndarray, ndarray, ndarray][source]
- deepmd.infer.model_devi.calc_model_devi_f(fs: ndarray, real_f: Optional[ndarray] = None, relative: Optional[float] = None, *, atomic: Literal[True]) Tuple[ndarray, ndarray, ndarray, ndarray]
Calculate model deviation of force.
- Parameters
- fs
numpy.ndarray size of n_models x n_frames x n_atoms x 3
- real_f
numpy.ndarrayorNone real force, size of n_frames x n_atoms x 3. If given, the RMS real error is calculated instead.
- relative
float, default:None If given, calculate the relative model deviation of force. The value is the level parameter for computing the relative model deviation of the force.
- atomicbool, default:
False Whether return deviation of force in all atoms
- fs
- Returns
- max_devi_f
numpy.ndarray maximum deviation of force in all atoms
- min_devi_f
numpy.ndarray minimum deviation of force in all atoms
- avg_devi_f
numpy.ndarray average deviation of force in all atoms
- fs_devi
numpy.ndarray deviation of force in all atoms, returned if atomic=True
- max_devi_f
- deepmd.infer.model_devi.calc_model_devi_v(vs: ndarray, real_v: Optional[ndarray] = None, relative: Optional[float] = None) Tuple[ndarray, ndarray, ndarray][source]
Calculate model deviation of virial.
- Parameters
- vs
numpy.ndarray size of n_models x n_frames x 9
- real_v
numpy.ndarray real virial, size of n_frames x 9. If given, the RMS real error is calculated instead.
- relative
float, default:None If given, calculate the relative model deviation of virial. The value is the level parameter for computing the relative model deviation of the virial.
- vs
- Returns
- max_devi_v
numpy.ndarray maximum deviation of virial in 9 elements
- min_devi_v
numpy.ndarray minimum deviation of virial in 9 elements
- avg_devi_v
numpy.ndarray average deviation of virial in 9 elements
- max_devi_v
- deepmd.infer.model_devi.make_model_devi(*, models: list, system: str, set_prefix: str, output: str, frequency: int, real_error: bool = False, atomic: bool = False, relative: Optional[float] = None, relative_v: Optional[float] = None, **kwargs)[source]
Make model deviation calculation.
- Parameters
- models
list A list of paths of models to use for making model deviation
- system
str The path of system to make model deviation calculation
- set_prefix
str The set prefix of the system
- output
str The output file for model deviation results
- frequency
int The number of steps that elapse between writing coordinates in a trajectory by a MD engine (such as Gromacs / Lammps). This paramter is used to determine the index in the output file.
- real_errorbool, default:
False If True, calculate the RMS real error instead of model deviation.
- atomicbool, default:
False If True, calculate the force model deviation of each atom.
- relative
float, default:None If given, calculate the relative model deviation of force. The value is the level parameter for computing the relative model deviation of the force.
- relative_v
float, default:None If given, calculate the relative model deviation of virial. The value is the level parameter for computing the relative model deviation of the virial.
- **kwargs
Arbitrary keyword arguments.
- models
- deepmd.infer.model_devi.write_model_devi_out(devi: ndarray, fname: str, header: str = '', atomic: bool = False)[source]
Write output of model deviation.
- Parameters
- devi
numpy.ndarray the first column is the steps index
- fname
str the file name to dump
- header
str, default=”” the header to dump
- atomicbool, default:
False whether atomic model deviation is printed
- devi
deepmd.loggers package
Alias of deepmd_utils.loggers for backward compatibility.
- deepmd.loggers.set_log_handles(level: int, log_path: Optional[Path] = None, mpi_log: Optional[str] = None)[source]
Set desired level for package loggers and add file handlers.
- Parameters
- level
int logging level
- log_path
Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None
- mpi_log
Optional[str],optional mpi log type. Has three options. master will output logs to file and console only from rank==0. collect will write messages from all ranks to one file opened under rank==0 and to console. workers will open one log file for each worker designated by its rank, console behaviour is the same as for collect. If this argument is specified, package ‘mpi4py’ must be already installed. by default None
- level
- Raises
RuntimeErrorIf the argument mpi_log is specified, package mpi4py is not installed.
Notes
Logging levels:
our notation
python logging
tensorflow cpp
OpenMP
debug
10
10
0
1/on/true/yes
info
20
20
1
0/off/false/no
warning
30
30
2
0/off/false/no
error
40
40
3
0/off/false/no
References
https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu
Submodules
deepmd.loggers.loggers module
Alias of deepmd_utils.loggers.loggers for backward compatibility.
- deepmd.loggers.loggers.set_log_handles(level: int, log_path: Optional[Path] = None, mpi_log: Optional[str] = None)[source]
Set desired level for package loggers and add file handlers.
- Parameters
- level
int logging level
- log_path
Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None
- mpi_log
Optional[str],optional mpi log type. Has three options. master will output logs to file and console only from rank==0. collect will write messages from all ranks to one file opened under rank==0 and to console. workers will open one log file for each worker designated by its rank, console behaviour is the same as for collect. If this argument is specified, package ‘mpi4py’ must be already installed. by default None
- level
- Raises
RuntimeErrorIf the argument mpi_log is specified, package mpi4py is not installed.
Notes
Logging levels:
our notation
python logging
tensorflow cpp
OpenMP
debug
10
10
0
1/on/true/yes
info
20
20
1
0/off/false/no
warning
30
30
2
0/off/false/no
error
40
40
3
0/off/false/no
References
https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu
deepmd.loss package
- class deepmd.loss.DOSLoss(starter_learning_rate: float, numb_dos: int = 500, start_pref_dos: float = 1.0, limit_pref_dos: float = 1.0, start_pref_cdf: float = 1000, limit_pref_cdf: float = 1.0, start_pref_ados: float = 0.0, limit_pref_ados: float = 0.0, start_pref_acdf: float = 0.0, limit_pref_acdf: float = 0.0, protect_value: float = 1e-08, log_fit: bool = False, **kwargs)[source]
Bases:
LossLoss function for DeepDOS models.
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.EnerDipoleLoss(starter_learning_rate: float, start_pref_e: float = 0.1, limit_pref_e: float = 1.0, start_pref_ed: float = 1.0, limit_pref_ed: float = 1.0)[source]
Bases:
LossMethods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.EnerSpinLoss(starter_learning_rate: float, start_pref_e: float = 0.02, limit_pref_e: float = 1.0, start_pref_fr: float = 1000, limit_pref_fr: float = 1.0, start_pref_fm: float = 10000, limit_pref_fm: float = 10.0, start_pref_v: float = 0.0, limit_pref_v: float = 0.0, start_pref_ae: float = 0.0, limit_pref_ae: float = 0.0, start_pref_pf: float = 0.0, limit_pref_pf: float = 0.0, relative_f: Optional[float] = None, enable_atom_ener_coeff: bool = False, use_spin: Optional[list] = None)[source]
Bases:
LossMethods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
print_header
print_on_training
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.EnerStdLoss(starter_learning_rate: float, start_pref_e: float = 0.02, limit_pref_e: float = 1.0, start_pref_f: float = 1000, limit_pref_f: float = 1.0, start_pref_v: float = 0.0, limit_pref_v: float = 0.0, start_pref_ae: float = 0.0, limit_pref_ae: float = 0.0, start_pref_pf: float = 0.0, limit_pref_pf: float = 0.0, relative_f: Optional[float] = None, enable_atom_ener_coeff: bool = False, start_pref_gf: float = 0.0, limit_pref_gf: float = 0.0, numb_generalized_coord: int = 0, **kwargs)[source]
Bases:
LossStandard loss function for DP models.
- Parameters
- starter_learning_rate
float The learning rate at the start of the training.
- start_pref_e
float The prefactor of energy loss at the start of the training.
- limit_pref_e
float The prefactor of energy loss at the end of the training.
- start_pref_f
float The prefactor of force loss at the start of the training.
- limit_pref_f
float The prefactor of force loss at the end of the training.
- start_pref_v
float The prefactor of virial loss at the start of the training.
- limit_pref_v
float The prefactor of virial loss at the end of the training.
- start_pref_ae
float The prefactor of atomic energy loss at the start of the training.
- limit_pref_ae
float The prefactor of atomic energy loss at the end of the training.
- start_pref_pf
float The prefactor of atomic prefactor force loss at the start of the training.
- limit_pref_pf
float The prefactor of atomic prefactor force loss at the end of the training.
- relative_f
float If provided, relative force error will be used in the loss. The difference of force will be normalized by the magnitude of the force in the label with a shift given by relative_f
- enable_atom_ener_coeffbool
if true, the energy will be computed as sum_i c_i E_i
- start_pref_gf
float The prefactor of generalized force loss at the start of the training.
- limit_pref_gf
float The prefactor of generalized force loss at the end of the training.
- numb_generalized_coord
int The dimension of generalized coordinates.
- **kwargs
Other keyword arguments.
- starter_learning_rate
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.TensorLoss(jdata, **kwarg)[source]
Bases:
LossLoss function for tensorial properties.
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
Submodules
deepmd.loss.dos module
- class deepmd.loss.dos.DOSLoss(starter_learning_rate: float, numb_dos: int = 500, start_pref_dos: float = 1.0, limit_pref_dos: float = 1.0, start_pref_cdf: float = 1000, limit_pref_cdf: float = 1.0, start_pref_ados: float = 0.0, limit_pref_ados: float = 0.0, start_pref_acdf: float = 0.0, limit_pref_acdf: float = 0.0, protect_value: float = 1e-08, log_fit: bool = False, **kwargs)[source]
Bases:
LossLoss function for DeepDOS models.
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
deepmd.loss.ener module
- class deepmd.loss.ener.EnerDipoleLoss(starter_learning_rate: float, start_pref_e: float = 0.1, limit_pref_e: float = 1.0, start_pref_ed: float = 1.0, limit_pref_ed: float = 1.0)[source]
Bases:
LossMethods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.ener.EnerSpinLoss(starter_learning_rate: float, start_pref_e: float = 0.02, limit_pref_e: float = 1.0, start_pref_fr: float = 1000, limit_pref_fr: float = 1.0, start_pref_fm: float = 10000, limit_pref_fm: float = 10.0, start_pref_v: float = 0.0, limit_pref_v: float = 0.0, start_pref_ae: float = 0.0, limit_pref_ae: float = 0.0, start_pref_pf: float = 0.0, limit_pref_pf: float = 0.0, relative_f: Optional[float] = None, enable_atom_ener_coeff: bool = False, use_spin: Optional[list] = None)[source]
Bases:
LossMethods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
print_header
print_on_training
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
- class deepmd.loss.ener.EnerStdLoss(starter_learning_rate: float, start_pref_e: float = 0.02, limit_pref_e: float = 1.0, start_pref_f: float = 1000, limit_pref_f: float = 1.0, start_pref_v: float = 0.0, limit_pref_v: float = 0.0, start_pref_ae: float = 0.0, limit_pref_ae: float = 0.0, start_pref_pf: float = 0.0, limit_pref_pf: float = 0.0, relative_f: Optional[float] = None, enable_atom_ener_coeff: bool = False, start_pref_gf: float = 0.0, limit_pref_gf: float = 0.0, numb_generalized_coord: int = 0, **kwargs)[source]
Bases:
LossStandard loss function for DP models.
- Parameters
- starter_learning_rate
float The learning rate at the start of the training.
- start_pref_e
float The prefactor of energy loss at the start of the training.
- limit_pref_e
float The prefactor of energy loss at the end of the training.
- start_pref_f
float The prefactor of force loss at the start of the training.
- limit_pref_f
float The prefactor of force loss at the end of the training.
- start_pref_v
float The prefactor of virial loss at the start of the training.
- limit_pref_v
float The prefactor of virial loss at the end of the training.
- start_pref_ae
float The prefactor of atomic energy loss at the start of the training.
- limit_pref_ae
float The prefactor of atomic energy loss at the end of the training.
- start_pref_pf
float The prefactor of atomic prefactor force loss at the start of the training.
- limit_pref_pf
float The prefactor of atomic prefactor force loss at the end of the training.
- relative_f
float If provided, relative force error will be used in the loss. The difference of force will be normalized by the magnitude of the force in the label with a shift given by relative_f
- enable_atom_ener_coeffbool
if true, the energy will be computed as sum_i c_i E_i
- start_pref_gf
float The prefactor of generalized force loss at the start of the training.
- limit_pref_gf
float The prefactor of generalized force loss at the end of the training.
- numb_generalized_coord
int The dimension of generalized coordinates.
- **kwargs
Other keyword arguments.
- starter_learning_rate
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
deepmd.loss.loss module
- class deepmd.loss.loss.Loss[source]
Bases:
objectThe abstract class for the loss function.
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- abstract build(learning_rate: Tensor, natoms: Tensor, model_dict: Dict[str, Tensor], label_dict: Dict[str, Tensor], suffix: str) Tuple[Tensor, Dict[str, Tensor]][source]
Build the loss function graph.
- Parameters
- Returns
- static display_if_exist(loss: Tensor, find_property: float) Tensor[source]
Display NaN if labeled property is not found.
deepmd.loss.tensor module
- class deepmd.loss.tensor.TensorLoss(jdata, **kwarg)[source]
Bases:
LossLoss function for tensorial properties.
Methods
build(learning_rate, natoms, model_dict, ...)Build the loss function graph.
display_if_exist(loss, find_property)Display NaN if labeled property is not found.
eval(sess, feed_dict, natoms)Eval the loss function.
- build(learning_rate, natoms, model_dict, label_dict, suffix)[source]
Build the loss function graph.
- Parameters
- Returns
deepmd.model package
- class deepmd.model.DOSModel(*args, **kwargs)[source]
Bases:
StandardModelDOS model.
- Parameters
- descriptor
Descriptor
- fitting_net
Fitting net
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'dos'
- class deepmd.model.DipoleModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.EnerModel(*args, **kwargs)[source]
Bases:
StandardModelEnergy model.
- Parameters
- descriptor
Descriptor
- fitting_net
Fitting net
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
- use_srtab
The table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha
The short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin
The lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmin
The upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- srtab_add_biasbool
Whether add energy bias from the statistics of the data to short-range tabulated atomic energy. It only takes effect when use_srtab is provided.
- spin
spin
- data_stat_nsample
The number of training samples in a system to compute and change the energy bias.
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
natoms_match
natoms_not_match
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- change_energy_bias(data: DeepmdDataSystem, frozen_model: str, origin_type_map: list, full_type_map: str, bias_shift: str = 'delta') None[source]
Change the energy bias according to the input data and the pretrained model.
- Parameters
- data
DeepmdDataSystem The training data.
- frozen_model
str The path file of frozen model.
- origin_type_map
list The original type_map in dataset, they are targets to change the energy bias.
- full_type_map
str The full type_map in pretrained model
- bias_shift
str The mode for changing energy bias : [‘delta’, ‘statistic’] ‘delta’ : perform predictions on energies of target dataset,
and do least sqaure on the errors to obtain the target shift as bias.
‘statistic’ : directly use the statistic energy bias in the target dataset.
- data
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'ener'
- class deepmd.model.GlobalPolarModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.MultiModel(*args, **kwargs)[source]
Bases:
ModelMulti-task model.
- Parameters
- descriptor
Descriptor
- fitting_net_dict
Dictionary of fitting nets
- fitting_type_dict
deprecated argument
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
- use_srtab
The table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha
The short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin
The lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmin
The upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- enable_mixed_precision(mixed_prec: dict)[source]
Enable mixed precision for the model.
- Parameters
- mixed_prec
dict The mixed precision config
- mixed_prec
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'multi_task'
- class deepmd.model.PolarModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.WFCModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
Submodules
deepmd.model.dos module
- class deepmd.model.dos.DOSModel(*args, **kwargs)[source]
Bases:
StandardModelDOS model.
- Parameters
- descriptor
Descriptor
- fitting_net
Fitting net
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'dos'
deepmd.model.ener module
- class deepmd.model.ener.EnerModel(*args, **kwargs)[source]
Bases:
StandardModelEnergy model.
- Parameters
- descriptor
Descriptor
- fitting_net
Fitting net
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
- use_srtab
The table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha
The short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin
The lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmin
The upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- srtab_add_biasbool
Whether add energy bias from the statistics of the data to short-range tabulated atomic energy. It only takes effect when use_srtab is provided.
- spin
spin
- data_stat_nsample
The number of training samples in a system to compute and change the energy bias.
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
natoms_match
natoms_not_match
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- change_energy_bias(data: DeepmdDataSystem, frozen_model: str, origin_type_map: list, full_type_map: str, bias_shift: str = 'delta') None[source]
Change the energy bias according to the input data and the pretrained model.
- Parameters
- data
DeepmdDataSystem The training data.
- frozen_model
str The path file of frozen model.
- origin_type_map
list The original type_map in dataset, they are targets to change the energy bias.
- full_type_map
str The full type_map in pretrained model
- bias_shift
str The mode for changing energy bias : [‘delta’, ‘statistic’] ‘delta’ : perform predictions on energies of target dataset,
and do least sqaure on the errors to obtain the target shift as bias.
‘statistic’ : directly use the statistic energy bias in the target dataset.
- data
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'ener'
deepmd.model.frozen module
- class deepmd.model.frozen.FrozenModel(*args, **kwargs)[source]
Bases:
ModelLoad model from a frozen model, which cannot be trained.
- Parameters
- model_file
str The path to the frozen model
- model_file
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, input_dict: dict, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None) dict[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- enable_compression(suffix: str = '') None[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
deepmd.model.linear module
- class deepmd.model.linear.LinearEnergyModel(*args, **kwargs)[source]
Bases:
LinearModelLinear energy model make linear combinations of several existing energy models.
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_ntypes
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, input_dict: dict, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None) dict[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- model_type = 'ener'
- class deepmd.model.linear.LinearModel(*args, **kwargs)[source]
Bases:
ModelLinear model make linear combinations of several existing models.
- Parameters
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_ntypes
- enable_compression(suffix: str = '') None[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
deepmd.model.model module
- class deepmd.model.model.Model(*args, **kwargs)[source]
Bases:
ABCAbstract base model.
- Parameters
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_bias_nsample
The number of training samples in a system to compute and change the energy bias.
- data_stat_protect
Protect parameter for atomic energy regression
- use_srtab
The table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha
The short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin
The lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmin
The upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- srtab_add_biasbool
Whether add energy bias from the statistics of the data to short-range tabulated atomic energy. It only takes effect when use_srtab is provided.
- spin
spin
- compress
Compression information for internal use
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- abstract build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, input_dict: dict, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- build_descrpt(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, input_dict: dict, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None)[source]
Build the descriptor part of the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
tf.TensorThe descriptor tensor
- build_type_embedding(ntypes: int, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None) Tensor[source]
Build the type embedding part of the model.
- Parameters
- Returns
tf.TensorThe type embedding tensor
- change_energy_bias(data: DeepmdDataSystem, frozen_model: str, origin_type_map: list, full_type_map: str, bias_shift: str = 'delta') None[source]
Change the energy bias according to the input data and the pretrained model.
- Parameters
- data
DeepmdDataSystem The training data.
- frozen_model
str The path file of frozen model.
- origin_type_map
list The original type_map in dataset, they are targets to change the energy bias.
- full_type_map
str The full type_map in pretrained model
- bias_shift
str The mode for changing energy bias : [‘delta’, ‘statistic’] ‘delta’ : perform predictions on energies of target dataset,
and do least sqaure on the errors to obtain the target shift as bias.
‘statistic’ : directly use the statistic energy bias in the target dataset.
- data
- enable_compression(suffix: str = '')[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
- enable_mixed_precision(mixed_prec: dict)[source]
Enable mixed precision for the model.
- Parameters
- mixed_prec
dict The mixed precision config
- mixed_prec
- classmethod get_class_by_input(input: dict)[source]
Get the class by input data.
- Parameters
- input
dict The input data
- input
- get_feed_dict(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, **kwargs) Dict[str, Tensor][source]
Generate the feed_dict for current descriptor.
- Parameters
- coord_
tf.Tensor The coordinate of atoms
- atype_
tf.Tensor The type of atoms
- natoms
tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box
tf.Tensor The box. Can be generated by deepmd.model.make_stat_input
- mesh
tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- **kwargs
dict The additional arguments
- coord_
- Returns
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- class deepmd.model.model.StandardModel(*args, **kwargs)[source]
Bases:
ModelStandard model, which must contain a descriptor and a fitting.
- Parameters
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- enable_compression(suffix: str = '')[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
deepmd.model.model_stat module
Alias for backward compatibility.
- deepmd.model.model_stat.make_stat_input(data, nbatches, merge_sys=True)[source]
Pack data for statistics.
- Parameters
- Returns
- all_stat:
A dictionary of list of list storing data for stat. if merge_sys == False data can be accessed by
all_stat[key][sys_idx][batch_idx][frame_idx]
- else merge_sys == True can be accessed by
all_stat[key][batch_idx][frame_idx]
deepmd.model.multi module
- class deepmd.model.multi.MultiModel(*args, **kwargs)[source]
Bases:
ModelMulti-task model.
- Parameters
- descriptor
Descriptor
- fitting_net_dict
Dictionary of fitting nets
- fitting_type_dict
deprecated argument
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
- use_srtab
The table for the short-range pairwise interaction added on top of DP. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- smin_alpha
The short-range tabulated interaction will be swithed according to the distance of the nearest neighbor. This distance is calculated by softmin. This parameter is the decaying parameter in the softmin. It is only required when use_srtab is provided.
- sw_rmin
The lower boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
- sw_rmin
The upper boundary of the interpolation between short-range tabulated interaction and DP. It is only required when use_srtab is provided.
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
Get the number of atomic parameters.
Get the number of gridpoints in energy space.
Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- enable_mixed_precision(mixed_prec: dict)[source]
Enable mixed precision for the model.
- Parameters
- mixed_prec
dict The mixed precision config
- mixed_prec
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'multi_task'
deepmd.model.pairtab module
- class deepmd.model.pairtab.PairTabModel(*args, **kwargs)[source]
Bases:
ModelPairwise tabulation energy model.
This model can be used to tabulate the pairwise energy between atoms for either short-range or long-range interactions, such as D3, LJ, ZBL, etc. It should not be used alone, but rather as one submodel of a linear (sum) model, such as DP+D3.
Do not put the model on the first model of a linear model, since the linear model fetches the type map from the first model.
At this moment, the model does not smooth the energy at the cutoff radius, so one needs to make sure the energy has been smoothed to zero.
- Parameters
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, input_dict: dict, frz_model: Optional[str] = None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[Union[bool, Enum]] = None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- enable_compression(suffix: str = '') None[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'ener'
deepmd.model.pairwise_dprc module
- class deepmd.model.pairwise_dprc.PairwiseDPRc(*args, **kwargs)[source]
Bases:
ModelPairwise Deep Potential - Range Correction.
Methods
build(coord_, atype_, natoms, box_, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
- build(coord_: Tensor, atype_: Tensor, natoms: Tensor, box_: Tensor, mesh: Tensor, input_dict: dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix: str = '', reuse: Optional[bool] = None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- enable_compression(suffix: str = '') None[source]
Enable compression.
- Parameters
- suffix
str suffix to name scope
- suffix
- get_feed_dict(coord_: Tensor, atype_: Tensor, natoms: Tensor, box: Tensor, mesh: Tensor, **kwargs) Dict[str, Tensor][source]
Generate the feed_dict for current descriptor.
- Parameters
- coord_
tf.Tensor The coordinate of atoms
- atype_
tf.Tensor The type of atoms
- natoms
tf.Tensor The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- box
tf.Tensor The box. Can be generated by deepmd.model.make_stat_input
- mesh
tf.Tensor For historical reasons, only the length of the Tensor matters. if size of mesh == 6, pbc is assumed. if size of mesh == 0, no-pbc is assumed.
- aparam
tf.Tensor The parameters of the descriptor
- **kwargs
dict The keyword arguments
- coord_
- Returns
- init_variables(graph: Graph, graph_def: GraphDef, model_type: str = 'original_model', suffix: str = '') None[source]
Init the embedding net variables with the given frozen model.
- model_type = 'ener'
deepmd.model.tensor module
- class deepmd.model.tensor.DipoleModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.tensor.GlobalPolarModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.tensor.PolarModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- class deepmd.model.tensor.TensorModel(*args, **kwargs)[source]
Bases:
StandardModelTensor model.
- Parameters
- tensor_name
Name of the tensor.
- descriptor
Descriptor
- fitting_net
Fitting net
- type_embedding
Type embedding net
- type_map
Mapping atom type to the name (str) of the type. For example type_map[1] gives the name of the type 1.
- data_stat_nbatch
Number of frames used for data statistic
- data_stat_protect
Protect parameter for atomic energy regression
Methods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
- build(coord_, atype_, natoms, box, mesh, input_dict, frz_model=None, ckpt_meta: Optional[str] = None, suffix='', reuse=None)[source]
Build the model.
- Parameters
- coord_
tf.Tensor The coordinates of atoms
- atype_
tf.Tensor The atom types of atoms
- natoms
tf.Tensor The number of atoms
- box
tf.Tensor The box vectors
- mesh
tf.Tensor The mesh vectors
- input_dict
dict The input dict
- frz_model
str,optional The path to the frozen model
- ckpt_meta
str,optional The path prefix of the checkpoint and meta files
- suffix
str,optional The suffix of the scope
- reusebool or
tf.AUTO_REUSE,optional Whether to reuse the variables
- coord_
- Returns
dictThe output dict
- class deepmd.model.tensor.WFCModel(*args, **kwargs)[source]
Bases:
TensorModelMethods
build(coord_, atype_, natoms, box, mesh, ...)Build the model.
build_descrpt(coord_, atype_, natoms, box, ...)Build the descriptor part of the model.
build_type_embedding(ntypes[, frz_model, ...])Build the type embedding part of the model.
change_energy_bias(data, frozen_model, ...)Change the energy bias according to the input data and the pretrained model.
data_stat(data)Data staticis.
enable_compression([suffix])Enable compression.
enable_mixed_precision(mixed_prec)Enable mixed precision for the model.
get_class_by_input(input)Get the class by input data.
get_feed_dict(coord_, atype_, natoms, box, ...)Generate the feed_dict for current descriptor.
get_fitting()Get the fitting(s).
get_loss(loss, lr)Get the loss function(s).
get_ntypes()Get the number of types.
get_numb_aparam()Get the number of atomic parameters.
get_numb_dos()Get the number of gridpoints in energy space.
get_numb_fparam()Get the number of frame parameters.
get_rcut()Get cutoff radius of the model.
get_type_map()Get the type map.
init_variables(graph, graph_def[, ...])Init the embedding net variables with the given frozen model.
update_sel(global_jdata, local_jdata)Update the selection and perform neighbor statistics.
get_out_size
get_sel_type
deepmd.nvnmd package
Subpackages
nvnmd.data ==========.
- Provides
hardware configuration
default input script
title and citation
- jdata_sys
action configuration
- jdata_config
hardware configuration
- dscp
descriptor configuration
- fitn
fitting network configuration
- size
ram capacity
- ctrl
control flag, such as Time Division Multiplexing (TDM)
- nbit
number of bits of fixed-point number
- jdata_config_16 (disable)
difference with configure fitting size as 16
- jdata_config_32 (disable)
difference with configure fitting size as 32
- jdata_config_64 (disable)
difference with configure fitting size as 64
- jdata_config_128 (default)
difference with configure fitting size as 128
- jdata_configs
all configure of jdata_config{nfit_node}
- jdata_deepmd_input
default input script for nvnmd training
- NVNMD_WELCOME
nvnmd title when logging
- NVNMD_CITATION
citation of nvnmd
nvnmd.se_a ==========.
- Provides
building descriptor with continuous embedding network
building descriptor with quantized embedding network
- deepmd.nvnmd.descriptor.se_a.build_davg_dstd()[source]
Get the davg and dstd from the dictionary nvnmd_cfg. The davg and dstd have been obtained by training CNN.
- deepmd.nvnmd.descriptor.se_a.check_switch_range(davg, dstd)[source]
Check the range of switch, let it in range [-2, 14].
- deepmd.nvnmd.descriptor.se_atten.build_davg_dstd()[source]
Get the davg and dstd from the dictionary nvnmd_cfg. The davg and dstd have been obtained by training CNN.
- deepmd.nvnmd.descriptor.se_atten.check_switch_range(davg, dstd)[source]
Check the range of switch, let it in range [-2, 14].
- class deepmd.nvnmd.entrypoints.MapTable(config_file: str, weight_file: str, map_file: str)[source]
Bases:
objectGenerate the mapping table describing the relastionship of atomic distance, cutoff function, and embedding matrix.
three mapping table will be built:
\(r^2_{ji} \rightarrow s_{ji}\)\(r^2_{ji} \rightarrow h_{ji}\)\(r^2_{ji} \rightarrow \mathcal{G}_{ji}\)where \(s_{ji}\) is cut-off function, \(h_{ji} = \frac{s(r_{ji})}{r_{ji}}\), and \(\mathcal{G}_{ji}\) is embedding matrix.
The mapping funciton can be define as:
\(y = f(x) = y_{k} + (x - x_{k}) * dy_{k}\)\(y_{k} = f(x_{k})\)\(dy_{k} = \frac{f(x_{k+1}) - f(x_{k})}{dx}\)\(x_{k} \leq x < x_{k+1}\)\(x_{k} = k * dx\)where \(dx\) is interpolation interval.
- Parameters
- config_file
input file name an .npy file containing the configuration information of NVNMD model
- weight_file
input file name an .npy file containing the weights of NVNMD model
- map_file
output file name an .npy file containing the mapping tables of NVNMD model
References
DOI: 10.1038/s41524-022-00773-z
Methods
build_grad(x, y, Nr, Nc): Build gradient of tensor y of x.
build_map_coef(cfgs, x, ys, grads, ...)Build mapping table coefficient cfgs: cfg list cfg = x0, x1, dx.
build_s2g(s)Build s->G s is switch function G is embedding net output.
Build gradient of G with respect to s.
Build t->G t is chemical species of center atom and neighbor atom G is embedding net output of type.
build_u2s(r2)Build tensor s, s=s(r2).
Build gradient of s with respect to u (r^2).
cal_coef4(cfgs, x, y, dy)Build mapping table coefficient for one line coef4: a x^3 + b x^2 + c x + d = y: / d = y0 | c = y0' | b = (3 y1 - dx dy' - 2dx y0' - 3y0) / dx^2 a = (dx y1' - 2 y1 + dx y0' + 2 y0) / dx^3.
mapping(x, dic_map, cfgs)Evaluate value by mapping table operation of tensorflow.
mapping2(x, dic_map, cfgs)Evaluate value by mapping table of numpy.
plot_lines(x, dic1[, dic2])Plot lines to see accuracy.
run_s2g()Build s-> graph and run it to get value of mapping table.
run_t2g()Build t-> graph and run it to get value of mapping table.
run_u2s()Build u->s graph and run it to get value of mapping table.
build_davg_dstd
build_embedding_net
build_map
- build_map_coef(cfgs, x, ys, grads, grad_grads, Nr, Nc)[source]
Build mapping table coefficient cfgs: cfg list cfg = x0, x1, dx.
coef4: a x^3 + b x^2 + c x + d = y: / d = y0 | c = y0’ | b = (3 y1 - dx dy’ - 2dx y0’ - 3y0) / dx^2 a = (dx y1’ - 2 y1 + dx y0’ + 2 y0) / dx^3
- build_t2g()[source]
Build t->G t is chemical species of center atom and neighbor atom G is embedding net output of type.
- class deepmd.nvnmd.entrypoints.Wrap(config_file: str, weight_file: str, map_file: str, model_file: str)[source]
Bases:
objectGenerate the binary model file (model.pb).
the model file can be use to run the NVNMD with lammps the pair style need set as:
pair_style nvnmd model.pb pair_coeff * *
- Parameters
- config_file
input file name an .npy file containing the configuration information of NVNMD model
- weight_file
input file name an .npy file containing the weights of NVNMD model
- map_file
input file name an .npy file containing the mapping tables of NVNMD model
- model_file
output file name an .pb file containing the model using in the NVNMD
References
DOI: 10.1038/s41524-022-00773-z
Methods
Wrap the configuration of descriptor.
Wrap the weights of fitting net.
wrap_head(nhs, nws)Wrap the head information.
wrap_lut()Wrap the LUT.
wrap_map()Wrap the mapping table of embedding network.
wrap_weight(weight, NBIT_DISP, NBIT_WEIGHT)weight: weights of fittingNet NBIT_DISP: nbits of exponent of weight max value NBIT_WEIGHT: nbits of mantissa of weights.
wrap
wrap_bias
- wrap_dscp()[source]
Wrap the configuration of descriptor.
version 0: [NBIT_IDX_S2G-1:0] SHIFT_IDX_S2G
[NBIT_NEIB*NTYPE-1:0] SELs [NBIT_FIXD*M1*NTYPE*NTYPE-1:0] GSs [NBIT_FLTE-1:0] NEXPO_DIV_NI
version 1:
[NBIT_FLTE-1:0] NEXPO_DIV_NI
- deepmd.nvnmd.entrypoints.save_weight(sess, file_name: str = 'nvnmd/weight.npy')[source]
Save the dictionary of weight to a npy file.
- deepmd.nvnmd.entrypoints.freeze.filter_tensorVariableList(tensorVariableList) dict[source]
Get the name of variable for NVNMD.
train_attr/min_nbor_distdescrpt_attr/t_avg:0descrpt_attr/t_std:0type_embed_net/matrix_{layer l}:0type_embed_net/bias_{layer l}:0version 0: |
filter_type_{atom i}/matrix_{layer l}_{atomj}:0filter_type_{atom i}/bias_{layer l}_{atomj}:0layer_{layer l}_type_{atom i}/matrix:0layer_{layer l}_type_{atom i}/bias:0final_layer_type_{atom i}/matrix:0final_layer_type_{atom i}/bias:0version 1: |
filter_type_all/matrix_{layer l}:0filter_type_all/bias_{layer l}:0filter_type_all/matrix_{layer l}_two_side_ebd:0filter_type_all/bias_{layer l}_two_side_ebd:0layer_{layer l}/matrix:0layer_{layer l}/bias:0final_layer/matrix:0final_layer/bias:0
- class deepmd.nvnmd.entrypoints.mapt.MapTable(config_file: str, weight_file: str, map_file: str)[source]
Bases:
objectGenerate the mapping table describing the relastionship of atomic distance, cutoff function, and embedding matrix.
three mapping table will be built:
\(r^2_{ji} \rightarrow s_{ji}\)\(r^2_{ji} \rightarrow h_{ji}\)\(r^2_{ji} \rightarrow \mathcal{G}_{ji}\)where \(s_{ji}\) is cut-off function, \(h_{ji} = \frac{s(r_{ji})}{r_{ji}}\), and \(\mathcal{G}_{ji}\) is embedding matrix.
The mapping funciton can be define as:
\(y = f(x) = y_{k} + (x - x_{k}) * dy_{k}\)\(y_{k} = f(x_{k})\)\(dy_{k} = \frac{f(x_{k+1}) - f(x_{k})}{dx}\)\(x_{k} \leq x < x_{k+1}\)\(x_{k} = k * dx\)where \(dx\) is interpolation interval.
- Parameters
- config_file
input file name an .npy file containing the configuration information of NVNMD model
- weight_file
input file name an .npy file containing the weights of NVNMD model
- map_file
output file name an .npy file containing the mapping tables of NVNMD model
References
DOI: 10.1038/s41524-022-00773-z
Methods
build_grad(x, y, Nr, Nc): Build gradient of tensor y of x.
build_map_coef(cfgs, x, ys, grads, ...)Build mapping table coefficient cfgs: cfg list cfg = x0, x1, dx.
build_s2g(s)Build s->G s is switch function G is embedding net output.
Build gradient of G with respect to s.
Build t->G t is chemical species of center atom and neighbor atom G is embedding net output of type.
build_u2s(r2)Build tensor s, s=s(r2).
Build gradient of s with respect to u (r^2).
cal_coef4(cfgs, x, y, dy)Build mapping table coefficient for one line coef4: a x^3 + b x^2 + c x + d = y: / d = y0 | c = y0' | b = (3 y1 - dx dy' - 2dx y0' - 3y0) / dx^2 a = (dx y1' - 2 y1 + dx y0' + 2 y0) / dx^3.
mapping(x, dic_map, cfgs)Evaluate value by mapping table operation of tensorflow.
mapping2(x, dic_map, cfgs)Evaluate value by mapping table of numpy.
plot_lines(x, dic1[, dic2])Plot lines to see accuracy.
run_s2g()Build s-> graph and run it to get value of mapping table.
run_t2g()Build t-> graph and run it to get value of mapping table.
run_u2s()Build u->s graph and run it to get value of mapping table.
build_davg_dstd
build_embedding_net
build_map
- build_map_coef(cfgs, x, ys, grads, grad_grads, Nr, Nc)[source]
Build mapping table coefficient cfgs: cfg list cfg = x0, x1, dx.
coef4: a x^3 + b x^2 + c x + d = y: / d = y0 | c = y0’ | b = (3 y1 - dx dy’ - 2dx y0’ - 3y0) / dx^2 a = (dx y1’ - 2 y1 + dx y0’ + 2 y0) / dx^3
- build_t2g()[source]
Build t->G t is chemical species of center atom and neighbor atom G is embedding net output of type.
- deepmd.nvnmd.entrypoints.train.normalized_input(fn, PATH_CNN, CONFIG_CNN)[source]
Normalize a input script file for continuous neural network.
- class deepmd.nvnmd.entrypoints.wrap.Wrap(config_file: str, weight_file: str, map_file: str, model_file: str)[source]
Bases:
objectGenerate the binary model file (model.pb).
the model file can be use to run the NVNMD with lammps the pair style need set as:
pair_style nvnmd model.pb pair_coeff * *
- Parameters
- config_file
input file name an .npy file containing the configuration information of NVNMD model
- weight_file
input file name an .npy file containing the weights of NVNMD model
- map_file
input file name an .npy file containing the mapping tables of NVNMD model
- model_file
output file name an .pb file containing the model using in the NVNMD
References
DOI: 10.1038/s41524-022-00773-z
Methods
Wrap the configuration of descriptor.
Wrap the weights of fitting net.
wrap_head(nhs, nws)Wrap the head information.
wrap_lut()Wrap the LUT.
wrap_map()Wrap the mapping table of embedding network.
wrap_weight(weight, NBIT_DISP, NBIT_WEIGHT)weight: weights of fittingNet NBIT_DISP: nbits of exponent of weight max value NBIT_WEIGHT: nbits of mantissa of weights.
wrap
wrap_bias
- wrap_dscp()[source]
Wrap the configuration of descriptor.
version 0: [NBIT_IDX_S2G-1:0] SHIFT_IDX_S2G
[NBIT_NEIB*NTYPE-1:0] SELs [NBIT_FIXD*M1*NTYPE*NTYPE-1:0] GSs [NBIT_FLTE-1:0] NEXPO_DIV_NI
version 1:
[NBIT_FLTE-1:0] NEXPO_DIV_NI
nvnmd.fit =========.
- Provides
continuous fitting network
quantized fitting network
- deepmd.nvnmd.fit.ener.one_layer_nvnmd(inputs, outputs_size, activation_fn=<function tanh>, precision=tf.float64, stddev=1.0, bavg=0.0, name='linear', reuse=None, seed=None, use_timestep=False, trainable=True, useBN=False, uniform_seed=False, initial_variables=None, mixed_prec=None, final_layer=False)
Build one layer with continuous or quantized value. Its weight and bias can be initialed with random or constant value.
- class deepmd.nvnmd.utils.Encode[source]
Bases:
objectEncoding value as hex, bin, and dec format.
Methods
bin2hex(data)Convert binary string list to hex string list.
bin2hex_str(sbin)Convert binary string to hex string.
byte2hex(bs, nbyte)Convert byte into hex bs: low byte in the first hex: low byte in the right.
check_dec(idec, nbit[, signed, name])Check whether the data (idec) is in the range range is \([0, 2^nbit-1]\) for unsigned range is \([-2^{nbit-1}, 2^{nbit-1}-1]\) for signed.
dec2bin(idec[, nbit, signed, name])Convert dec array to binary string list.
extend_bin(slbin, nfull)Extend the element of list (slbin) to the length (nfull).
extend_hex(slhex, nfull)Extend the element of list (slhex) to the length (nfull).
extend_list(slbin, nfull)Extend the list (slbin) to the length (nfull) the attched element of list is 0.
flt2bin(data, nbit_expo, nbit_frac)Convert float into binary string list.
hex2bin(data)Convert hex string list to binary string list.
hex2bin_str(shex)Convert hex string to binary string.
merge_bin(slbin, nmerge)Merge binary string list per nmerge value.
qc(v[, nbit])Quantize value using ceil.
qf(v[, nbit])Quantize value using floor.
qr(v[, nbit])Quantize value using round.
reverse_bin(slbin, nreverse)Reverse binary string list per nreverse value.
split_bin(sbin, nbit)Split sbin into many segment with the length nbit.
find_max_expo
flt2bin_one
norm_expo
split_expo_mant
- byte2hex(bs, nbyte)[source]
Convert byte into hex bs: low byte in the first hex: low byte in the right.
- check_dec(idec, nbit, signed=False, name='')[source]
Check whether the data (idec) is in the range range is \([0, 2^nbit-1]\) for unsigned range is \([-2^{nbit-1}, 2^{nbit-1}-1]\) for signed.
- extend_bin(slbin, nfull)[source]
Extend the element of list (slbin) to the length (nfull).
such as, when
slbin = [‘10010’,’10100’],nfull = 6extent to
[‘010010’,’010100’]
- class deepmd.nvnmd.utils.FioBin[source]
Bases:
objectInput and output for binary file.
Methods
load([file_name, default_value])Load binary file into bytes value.
save(file_name, data)Save hex string into binary file.
- class deepmd.nvnmd.utils.FioDic[source]
Bases:
objectInput and output for dict class data the file can be .json or .npy file containing a dictionary.
Methods
update(jdata, jdata_o)Update key-value pair is key in jdata_o.keys().
get
load
save
- class deepmd.nvnmd.utils.FioTxt[source]
Bases:
objectInput and output for .txt file with string.
Methods
load([file_name, default_value])Load .txt file into string list.
save([file_name, data])Save string list into .txt file.
- deepmd.nvnmd.utils.get_filter_weight(weights: int, spe_j: int, layer_l: int)[source]
Get weight and bias of embedding network.
- deepmd.nvnmd.utils.get_fitnet_weight(weights: dict, spe_i: int, layer_l: int, nlayer: int = 10)[source]
Get weight and bias of fitting network.
- deepmd.nvnmd.utils.map_nvnmd(x, map_y, map_dy, prec, nbit=None)[source]
Mapping function implemented by numpy.
- deepmd.nvnmd.utils.one_layer(inputs, outputs_size, activation_fn=<function tanh>, precision=tf.float64, stddev=1.0, bavg=0.0, name='linear', reuse=None, seed=None, use_timestep=False, trainable=True, useBN=False, uniform_seed=False, initial_variables=None, mixed_prec=None, final_layer=False)[source]
Build one layer with continuous or quantized value. Its weight and bias can be initialed with random or constant value.
Alias for backward compatibility.
- class deepmd.nvnmd.utils.config.NvnmdConfig(jdata: dict)[source]
Bases:
objectConfiguration for NVNMD record the message of model such as size, using nvnmd or not.
- Parameters
- jdata
a dictionary of input script
References
DOI: 10.1038/s41524-022-00773-z
Methods
Display the log of NVNMD.
Generate input script with member element one by one.
Build the weight dict for initialization of net.
Generate model/descriptor in input script.
Generate model/fitting_net in input script.
Generate learning_rate in input script.
Generate loss in input script.
Generate model in input script.
Generate nvnmd in input script.
get_s_range(davg, dstd)Get the range of switch function.
Generate training in input script.
init_config_by_version(version, max_nnei)Initialize version-dependent parameters.
init_ctrl(jdata[, jdata_parent])Initialize members about control signal.
init_dpin(jdata[, jdata_parent])Initialize members about other deepmd input.
init_dscp(jdata[, jdata_parent])Initialize members about descriptor.
init_fitn(jdata[, jdata_parent])Initialize members about fitting network.
init_from_config(jdata)Initialize member element one by one.
init_from_deepmd_input(jdata)Initialize members with input script of deepmd.
init_from_jdata([jdata])Initialize this class with jdata loaded from input script.
init_nbit(jdata[, jdata_parent])Initialize members about quantification precision.
Initialize net_size.
init_size(jdata[, jdata_parent])Initialize members about ram capacity.
init_train_mode([mod])Configure for taining cnn or qnn.
Initialize member with dict.
save([file_name])Save all configuration to file.
set_ntype(ntype)Set the number of type.
Update config from dict.
- init_ctrl(jdata: dict, jdata_parent: dict = {}) dict[source]
Initialize members about control signal.
- init_dpin(jdata: dict, jdata_parent: dict = {}) dict[source]
Initialize members about other deepmd input.
- init_fitn(jdata: dict, jdata_parent: dict = {}) dict[source]
Initialize members about fitting network.
- init_from_jdata(jdata: dict = {})[source]
Initialize this class with jdata loaded from input script.
- init_nbit(jdata: dict, jdata_parent: dict = {}) dict[source]
Initialize members about quantification precision.
- class deepmd.nvnmd.utils.encode.Encode[source]
Bases:
objectEncoding value as hex, bin, and dec format.
Methods
bin2hex(data)Convert binary string list to hex string list.
bin2hex_str(sbin)Convert binary string to hex string.
byte2hex(bs, nbyte)Convert byte into hex bs: low byte in the first hex: low byte in the right.
check_dec(idec, nbit[, signed, name])Check whether the data (idec) is in the range range is \([0, 2^nbit-1]\) for unsigned range is \([-2^{nbit-1}, 2^{nbit-1}-1]\) for signed.
dec2bin(idec[, nbit, signed, name])Convert dec array to binary string list.
extend_bin(slbin, nfull)Extend the element of list (slbin) to the length (nfull).
extend_hex(slhex, nfull)Extend the element of list (slhex) to the length (nfull).
extend_list(slbin, nfull)Extend the list (slbin) to the length (nfull) the attched element of list is 0.
flt2bin(data, nbit_expo, nbit_frac)Convert float into binary string list.
hex2bin(data)Convert hex string list to binary string list.
hex2bin_str(shex)Convert hex string to binary string.
merge_bin(slbin, nmerge)Merge binary string list per nmerge value.
qc(v[, nbit])Quantize value using ceil.
qf(v[, nbit])Quantize value using floor.
qr(v[, nbit])Quantize value using round.
reverse_bin(slbin, nreverse)Reverse binary string list per nreverse value.
split_bin(sbin, nbit)Split sbin into many segment with the length nbit.
find_max_expo
flt2bin_one
norm_expo
split_expo_mant
- byte2hex(bs, nbyte)[source]
Convert byte into hex bs: low byte in the first hex: low byte in the right.
- check_dec(idec, nbit, signed=False, name='')[source]
Check whether the data (idec) is in the range range is \([0, 2^nbit-1]\) for unsigned range is \([-2^{nbit-1}, 2^{nbit-1}-1]\) for signed.
- extend_bin(slbin, nfull)[source]
Extend the element of list (slbin) to the length (nfull).
such as, when
slbin = [‘10010’,’10100’],nfull = 6extent to
[‘010010’,’010100’]
- class deepmd.nvnmd.utils.fio.Fio[source]
Bases:
objectBasic class for FIO.
Methods
create_file_path
exits
get_file_list
is_file
is_path
mkdir
- class deepmd.nvnmd.utils.fio.FioBin[source]
Bases:
objectInput and output for binary file.
Methods
load([file_name, default_value])Load binary file into bytes value.
save(file_name, data)Save hex string into binary file.
- class deepmd.nvnmd.utils.fio.FioDic[source]
Bases:
objectInput and output for dict class data the file can be .json or .npy file containing a dictionary.
Methods
update(jdata, jdata_o)Update key-value pair is key in jdata_o.keys().
get
load
save
- class deepmd.nvnmd.utils.fio.FioJsonDic[source]
Bases:
objectInput and output for .json file containing dictionary.
Methods
load([file_name, default_value])Load .json file into dict.
save([file_name, dic])Save dict into .json file.
- class deepmd.nvnmd.utils.fio.FioNpyDic[source]
Bases:
objectInput and output for .npy file containing dictionary.
Methods
load
save
- deepmd.nvnmd.utils.network.matmul2_qq(a, b, nbit)[source]
Quantized matmul operation for 2d tensor. a and b is input tensor, nbit represent quantification precision.
- deepmd.nvnmd.utils.network.matmul3_qq(a, b, nbit)[source]
Quantized matmul operation for 3d tensor. a and b is input tensor, nbit represent quantification precision.
- deepmd.nvnmd.utils.network.one_layer(inputs, outputs_size, activation_fn=<function tanh>, precision=tf.float64, stddev=1.0, bavg=0.0, name='linear', reuse=None, seed=None, use_timestep=False, trainable=True, useBN=False, uniform_seed=False, initial_variables=None, mixed_prec=None, final_layer=False)[source]
Build one layer with continuous or quantized value. Its weight and bias can be initialed with random or constant value.
- deepmd.nvnmd.utils.network.one_layer_t(shape, outputs_size, bavg, stddev, precision, trainable, initial_variables, seed, uniform_seed, name)[source]
- deepmd.nvnmd.utils.network.one_layer_wb(shape, outputs_size, bavg, stddev, precision, trainable, initial_variables, seed, uniform_seed, name)[source]
- deepmd.nvnmd.utils.network.qf(x, nbit)[source]
Quantize and floor tensor x with quantification precision nbit.
- deepmd.nvnmd.utils.weight.get_constant_initializer(weights, name)[source]
Get initial value by name and create a initializer.
- deepmd.nvnmd.utils.weight.get_filter_type_weight(weights: dict, layer_l: int)[source]
Get weight and bias of two_side_type_embedding network.
- Parameters
- weights
dict weights
- layer_l
layer order in embedding network 1~nlayer
- weights
- deepmd.nvnmd.utils.weight.get_filter_weight(weights: int, spe_j: int, layer_l: int)[source]
Get weight and bias of embedding network.
- deepmd.nvnmd.utils.weight.get_fitnet_weight(weights: dict, spe_i: int, layer_l: int, nlayer: int = 10)[source]
Get weight and bias of fitting network.
- deepmd.nvnmd.utils.weight.get_normalize(weights: dict)[source]
Get normalize parameter (avg and std) of \(s_{ji}\).
- deepmd.nvnmd.utils.weight.get_type_embedding_weight(weights: dict, layer_l: int)[source]
Get weight and bias of type_embedding network.
- Parameters
- weights
dict weights
- layer_l
layer order in embedding network 1~nlayer
- weights
deepmd.op package
This module will house cust Tf OPs after CMake installation.
deepmd.train package
Submodules
deepmd.train.run_options module
Module taking care of important package constants.
- class deepmd.train.run_options.RunOptions(init_model: Optional[str] = None, init_frz_model: Optional[str] = None, finetune: Optional[str] = None, restart: Optional[str] = None, log_path: Optional[str] = None, log_level: int = 0, mpi_log: str = 'master')[source]
Bases:
objectClass with info on how to run training (cluster, MPI and GPU config).
- Attributes
- gpus: Optional[List[int]]
list of GPUs if any are present else None
- is_chief: bool
in distribured training it is true for tha main MPI process in serail it is always true
- world_size: int
total worker count
- my_rank: int
index of the MPI task
- nodename: str
name of the node
- node_list_
List[str] the list of nodes of the current mpirun
- my_device: str
deviice type - gpu or cpu
Methods
Print build and current running cluster configuration summary.
- property is_chief
Whether my rank is 0.
deepmd.train.trainer module
- class deepmd.train.trainer.DPTrainer(jdata, run_opt, is_compress=False)[source]
Bases:
objectMethods
Save the compressed graph.
build
eval_single_list
get_evaluation_results
get_feed_dict
get_global_step
print_header
print_on_training
save_checkpoint
train
valid_on_the_fly
- class deepmd.train.trainer.DatasetLoader(train_data: DeepmdDataSystem)[source]
Bases:
objectGenerate an OP that loads the training data from the given DeepmdDataSystem.
It can be used to load the training data in the training process, so there is no waiting time between training steps.
- Parameters
- train_data
DeepmdDataSystem The training data.
- train_data
Examples
>>> loader = DatasetLoader(train_data) >>> data_op = loader.build() >>> with tf.Session() as sess: >>> data_list = sess.run(data_op) >>> data_dict = loader.get_data_dict(data_list)
Methods
build()Build the OP that loads the training data.
get_data_dict(batch_list)Generate a dict of the loaded data.
deepmd.utils package
- class deepmd.utils.DeepmdData(sys_path: str, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set: bool = False, sort_atoms: bool = True)[source]
Bases:
objectClass for a data system.
It loads data from hard disk, and mantains the data as a data_dict
- Parameters
- sys_path
Path to the data system
- set_prefix
Prefix for the directories of different sets
- shuffle_test
If the test data are shuffled
- type_map
Gives the name of different atom types
- optional_type_map
If the type_map.raw in each system is optional
- modifier
Data modifier that has the method modify_data
- trn_all_set
Use all sets as training dataset. Otherwise, if the number of sets is more than 1, the last set is left for test.
- sort_atomsbool
Sort atoms by atom types. Required to enable when the data is directly feeded to descriptors except mixed types.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
avg(key)Return the average value of an item.
check_batch_size(batch_size)Check if the system can get a batch of data with batch_size frames.
check_test_size(test_size)Check if the system can get a test dataset with test_size frames.
Get atom types.
get_batch(batch_size)Get a batch of data with batch_size frames.
Get the data_dict.
Get number of atoms.
get_natoms_vec(ntypes)Get number of atoms and number of atoms in different types.
Number of atom types in the system.
get_numb_batch(batch_size, set_idx)Get the number of batches in a set.
Get number of training sets.
get_sys_numb_batch(batch_size)Get the number of batches in the data system.
get_test([ntests])Get the test data with ntests frames.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
reset_get_batch
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0, dtype: Optional[dtype] = None)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default
float, default=0. default value of data
- dtype
np.dtype,optional the dtype of data, overwrites high_prec if provided
- check_batch_size(batch_size)[source]
Check if the system can get a batch of data with batch_size frames.
- check_test_size(test_size)[source]
Check if the system can get a test dataset with test_size frames.
- get_batch(batch_size: int) dict[source]
Get a batch of data with batch_size frames. The frames are randomly picked from the data system.
- Parameters
- batch_size
size of the batch
- get_natoms_vec(ntypes: int)[source]
Get number of atoms and number of atoms in different types.
- Parameters
- ntypes
Number of types (may be larger than the actual number of types in the system).
- Returns
natomsnatoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- get_test(ntests: int = -1) dict[source]
Get the test data with ntests frames.
- Parameters
- ntests
Size of the test data set. If ntests is -1, all test data will be get.
- class deepmd.utils.DeepmdDataSystem(systems: List[str], batch_size: int, test_size: int, rcut: Optional[float] = None, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set=False, sys_probs=None, auto_prob_style='prob_sys_size', sort_atoms: bool = True)[source]
Bases:
objectClass for manipulating many data systems.
It is implemented with the help of DeepmdData
- Attributes
default_meshMesh for each system.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
add_dict(adict)Add items to the data system by a dict.
get_batch([sys_idx])Get a batch of data from the data systems.
Get a batch of data from the data systems in the mixed way.
Get the batch size.
get_batch_standard([sys_idx])Get a batch of data from the data systems in the standard way.
Get the total number of batches.
Get the number of data systems.
Get the number of types.
get_sys(idx)Get a certain data system.
get_sys_ntest([sys_idx])Get number of tests for the currently selected system, or one defined by sys_idx.
get_test([sys_idx, n_test])Get test data from the the data systems.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
compute_energy_shift
get_data_dict
print_summary
set_sys_probs
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default, default=0.
Default value of data
- add_dict(adict: dict) None[source]
Add items to the data system by a dict. adict should have items like .. code-block:: python.
- adict[key] = {
“ndof”: ndof, “atomic”: atomic, “must”: must, “high_prec”: high_prec, “type_sel”: type_sel, “repeat”: repeat,
}
For the explaination of the keys see add
- get_batch(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems.
- Parameters
- sys_idx
int The index of system from which the batch is get. If sys_idx is not None, sys_probs and auto_prob_style are ignored If sys_idx is None, automatically determine the system according to sys_probs or auto_prob_style, see the following. This option does not work for mixed systems.
- sys_idx
- Returns
dictThe batch data
- get_batch_mixed() dict[source]
Get a batch of data from the data systems in the mixed way.
- Returns
dictThe batch data
- get_batch_standard(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems in the standard way.
- get_sys(idx: int) DeepmdData[source]
Get a certain data system.
- get_sys_ntest(sys_idx=None)[source]
Get number of tests for the currently selected system, or one defined by sys_idx.
- get_test(sys_idx: Optional[int] = None, n_test: int = -1)[source]
Get test data from the the data systems.
- Parameters
- sys_idx
The test dat of system with index sys_idx will be returned. If is None, the currently selected system will be returned.
- n_test
Number of test data. If set to -1 all test data will be get.
- class deepmd.utils.LearningRateExp(start_lr: float, stop_lr: float = 5e-08, decay_steps: int = 5000, decay_rate: float = 0.95)[source]
Bases:
objectThe exponentially decaying learning rate.
The learning rate at step \(t\) is given by
\[\alpha(t) = \alpha_0 \lambda ^ { t / \tau }\]where \(\alpha\) is the learning rate, \(\alpha_0\) is the starting learning rate, \(\lambda\) is the decay rate, and \(\tau\) is the decay steps.
- Parameters
- start_lr
Starting learning rate \(\alpha_0\)
- stop_lr
Stop learning rate \(\alpha_1\)
- decay_steps
Learning rate decay every this number of steps \(\tau\)
- decay_rate
The decay rate \(\lambda\). If stop_step is provided in build, then it will be determined automatically and overwritten.
Methods
build(global_step[, stop_step])Build the learning rate.
start_lr()Get the start lr.
value(step)Get the lr at a certain step.
- build(global_step: Tensor, stop_step: Optional[int] = None) Tensor[source]
Build the learning rate.
- Parameters
- global_step
The tf Tensor prividing the global training step
- stop_step
The stop step. If provided, the decay_rate will be determined automatically and overwritten.
- Returns
learning_rateThe learning rate
- class deepmd.utils.PairTab(filename: str)[source]
Bases:
objectPairwise tabulated potential.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
Methods
get()Get the serialized table.
reinit(filename)Initialize the tabulated interaction.
- reinit(filename: str) None[source]
Initialize the tabulated interaction.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
- class deepmd.utils.Plugin[source]
Bases:
objectA class to register and restore plugins.
Examples
>>> plugin = Plugin() >>> @plugin.register("xx") def xxx(): pass >>> print(plugin.plugins['xx'])
Methods
get_plugin(key)Visit a plugin by key.
register(key)Register a plugin.
- class deepmd.utils.PluginVariant(*args, **kwargs)[source]
Bases:
objectA class to remove type from input arguments.
Submodules
deepmd.utils.argcheck module
Alias for backward compatibility.
deepmd.utils.batch_size module
- class deepmd.utils.batch_size.AutoBatchSize(initial_batch_size: int = 1024, factor: float = 2.0)[source]
Bases:
AutoBatchSizeMethods
execute(callable, start_index, natoms)Excuate a method with given batch size.
execute_all(callable, total_size, natoms, ...)Excuate a method with all given data.
Check if GPU is available.
is_oom_error(e)Check if the exception is an OOM error.
deepmd.utils.compat module
Alias for backward compatibility.
- deepmd.utils.compat.convert_input_v0_v1(jdata: Dict[str, Any], warning: bool = True, dump: Optional[Union[str, Path]] = None) Dict[str, Any][source]
Convert input from v0 format to v1.
- deepmd.utils.compat.convert_input_v1_v2(jdata: Dict[str, Any], warning: bool = True, dump: Optional[Union[str, Path]] = None) Dict[str, Any][source]
deepmd.utils.compress module
deepmd.utils.convert module
- deepmd.utils.convert.convert_012_to_21(input_model: str, output_model: str)[source]
Convert DP 0.12 graph to 2.1 graph.
- deepmd.utils.convert.convert_10_to_21(input_model: str, output_model: str)[source]
Convert DP 1.0 graph to 2.1 graph.
- deepmd.utils.convert.convert_12_to_21(input_model: str, output_model: str)[source]
Convert DP 1.2 graph to 2.1 graph.
- deepmd.utils.convert.convert_13_to_21(input_model: str, output_model: str)[source]
Convert DP 1.3 graph to 2.1 graph.
- deepmd.utils.convert.convert_20_to_21(input_model: str, output_model: str)[source]
Convert DP 2.0 graph to 2.1 graph.
- deepmd.utils.convert.convert_dp012_to_dp10(file: str)[source]
Convert DP 0.12 graph text to 1.0 graph text.
- Parameters
- file
str filename of the graph text
- file
- deepmd.utils.convert.convert_dp10_to_dp11(file: str)[source]
Convert DP 1.0 graph text to 1.1 graph text.
- Parameters
- file
str filename of the graph text
- file
- deepmd.utils.convert.convert_dp12_to_dp13(file: str)[source]
Convert DP 1.2 graph text to 1.3 graph text.
- Parameters
- file
str filename of the graph text
- file
- deepmd.utils.convert.convert_dp13_to_dp20(fname: str)[source]
Convert DP 1.3 graph text to 2.0 graph text.
- Parameters
- fname
str filename of the graph text
- fname
- deepmd.utils.convert.convert_pb_to_pbtxt(pbfile: str, pbtxtfile: str)[source]
Convert DP graph to graph text.
- deepmd.utils.convert.convert_pbtxt_to_pb(pbtxtfile: str, pbfile: str)[source]
Convert DP graph text to graph.
deepmd.utils.data module
Alias for backward compatibility.
- class deepmd.utils.data.DeepmdData(sys_path: str, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set: bool = False, sort_atoms: bool = True)[source]
Bases:
objectClass for a data system.
It loads data from hard disk, and mantains the data as a data_dict
- Parameters
- sys_path
Path to the data system
- set_prefix
Prefix for the directories of different sets
- shuffle_test
If the test data are shuffled
- type_map
Gives the name of different atom types
- optional_type_map
If the type_map.raw in each system is optional
- modifier
Data modifier that has the method modify_data
- trn_all_set
Use all sets as training dataset. Otherwise, if the number of sets is more than 1, the last set is left for test.
- sort_atomsbool
Sort atoms by atom types. Required to enable when the data is directly feeded to descriptors except mixed types.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
avg(key)Return the average value of an item.
check_batch_size(batch_size)Check if the system can get a batch of data with batch_size frames.
check_test_size(test_size)Check if the system can get a test dataset with test_size frames.
Get atom types.
get_batch(batch_size)Get a batch of data with batch_size frames.
Get the data_dict.
Get number of atoms.
get_natoms_vec(ntypes)Get number of atoms and number of atoms in different types.
Number of atom types in the system.
get_numb_batch(batch_size, set_idx)Get the number of batches in a set.
Get number of training sets.
get_sys_numb_batch(batch_size)Get the number of batches in the data system.
get_test([ntests])Get the test data with ntests frames.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
reset_get_batch
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0, dtype: Optional[dtype] = None)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default
float, default=0. default value of data
- dtype
np.dtype,optional the dtype of data, overwrites high_prec if provided
- check_batch_size(batch_size)[source]
Check if the system can get a batch of data with batch_size frames.
- check_test_size(test_size)[source]
Check if the system can get a test dataset with test_size frames.
- get_batch(batch_size: int) dict[source]
Get a batch of data with batch_size frames. The frames are randomly picked from the data system.
- Parameters
- batch_size
size of the batch
- get_natoms_vec(ntypes: int)[source]
Get number of atoms and number of atoms in different types.
- Parameters
- ntypes
Number of types (may be larger than the actual number of types in the system).
- Returns
natomsnatoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- get_test(ntests: int = -1) dict[source]
Get the test data with ntests frames.
- Parameters
- ntests
Size of the test data set. If ntests is -1, all test data will be get.
deepmd.utils.data_system module
Alias for backward compatibility.
- class deepmd.utils.data_system.DeepmdDataSystem(systems: List[str], batch_size: int, test_size: int, rcut: Optional[float] = None, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set=False, sys_probs=None, auto_prob_style='prob_sys_size', sort_atoms: bool = True)[source]
Bases:
objectClass for manipulating many data systems.
It is implemented with the help of DeepmdData
- Attributes
default_meshMesh for each system.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
add_dict(adict)Add items to the data system by a dict.
get_batch([sys_idx])Get a batch of data from the data systems.
Get a batch of data from the data systems in the mixed way.
Get the batch size.
get_batch_standard([sys_idx])Get a batch of data from the data systems in the standard way.
Get the total number of batches.
Get the number of data systems.
Get the number of types.
get_sys(idx)Get a certain data system.
get_sys_ntest([sys_idx])Get number of tests for the currently selected system, or one defined by sys_idx.
get_test([sys_idx, n_test])Get test data from the the data systems.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
compute_energy_shift
get_data_dict
print_summary
set_sys_probs
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default, default=0.
Default value of data
- add_dict(adict: dict) None[source]
Add items to the data system by a dict. adict should have items like .. code-block:: python.
- adict[key] = {
“ndof”: ndof, “atomic”: atomic, “must”: must, “high_prec”: high_prec, “type_sel”: type_sel, “repeat”: repeat,
}
For the explaination of the keys see add
- get_batch(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems.
- Parameters
- sys_idx
int The index of system from which the batch is get. If sys_idx is not None, sys_probs and auto_prob_style are ignored If sys_idx is None, automatically determine the system according to sys_probs or auto_prob_style, see the following. This option does not work for mixed systems.
- sys_idx
- Returns
dictThe batch data
- get_batch_mixed() dict[source]
Get a batch of data from the data systems in the mixed way.
- Returns
dictThe batch data
- get_batch_standard(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems in the standard way.
- get_sys(idx: int) DeepmdData[source]
Get a certain data system.
- get_sys_ntest(sys_idx=None)[source]
Get number of tests for the currently selected system, or one defined by sys_idx.
- get_test(sys_idx: Optional[int] = None, n_test: int = -1)[source]
Get test data from the the data systems.
- Parameters
- sys_idx
The test dat of system with index sys_idx will be returned. If is None, the currently selected system will be returned.
- n_test
Number of test data. If set to -1 all test data will be get.
deepmd.utils.errors module
deepmd.utils.finetune module
deepmd.utils.graph module
- deepmd.utils.graph.get_attention_layer_nodes_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the attention layer nodes with the given tf.GraphDef object.
- deepmd.utils.graph.get_attention_layer_variables_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the attention layer variables with the given tf.GraphDef object.
- deepmd.utils.graph.get_embedding_net_nodes(model_file: str, suffix: str = '') Dict[source]
Get the embedding net nodes with the given frozen model(model_file).
- deepmd.utils.graph.get_embedding_net_nodes_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the embedding net nodes with the given tf.GraphDef object.
- deepmd.utils.graph.get_embedding_net_variables(model_file: str, suffix: str = '') Dict[source]
Get the embedding net variables with the given frozen model(model_file).
- deepmd.utils.graph.get_embedding_net_variables_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the embedding net variables with the given tf.GraphDef object.
- deepmd.utils.graph.get_extra_embedding_net_suffix(type_one_side: bool)[source]
Get the extra embedding net suffix according to the value of type_one_side.
- Parameters
- type_one_side
The value of type_one_side
- Returns
strThe extra embedding net suffix
- deepmd.utils.graph.get_extra_embedding_net_variables_from_graph_def(graph_def: GraphDef, suffix: str, extra_suffix: str, layer_size: int)[source]
Get extra embedding net variables from the given tf.GraphDef object. The “extra embedding net” means the embedding net with only type embeddings input, which occurs in “se_atten_v2” and “se_a_ebd_v2” descriptor.
- Parameters
- Returns
DictThe extra embedding net variables within the given tf.GraphDef object
- deepmd.utils.graph.get_fitting_net_nodes(model_file: str) Dict[source]
Get the fitting net nodes with the given frozen model(model_file).
- Parameters
- model_file
The input frozen model path
- Returns
DictThe fitting net nodes with the given frozen model
- deepmd.utils.graph.get_fitting_net_nodes_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the fitting net nodes with the given tf.GraphDef object.
- Parameters
- graph_def
The input tf.GraphDef object
- suffix
suffix of the scope
- Returns
DictThe fitting net nodes within the given tf.GraphDef object
- deepmd.utils.graph.get_fitting_net_variables(model_file: str, suffix: str = '') Dict[source]
Get the fitting net variables with the given frozen model(model_file).
- Parameters
- model_file
The input frozen model path
- suffix
suffix of the scope
- Returns
DictThe fitting net variables within the given frozen model
- deepmd.utils.graph.get_fitting_net_variables_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the fitting net variables with the given tf.GraphDef object.
- Parameters
- graph_def
The input tf.GraphDef object
- suffix
suffix of the scope
- Returns
DictThe fitting net variables within the given tf.GraphDef object
- deepmd.utils.graph.get_pattern_nodes_from_graph_def(graph_def: GraphDef, pattern: str) Dict[source]
Get the pattern nodes with the given tf.GraphDef object.
- Parameters
- graph_def
The input tf.GraphDef object
- pattern
The node pattern within the graph_def
- Returns
DictThe fitting net nodes within the given tf.GraphDef object
- deepmd.utils.graph.get_tensor_by_name(model_file: str, tensor_name: str) Tensor[source]
Load tensor value from the frozen model(model_file).
- deepmd.utils.graph.get_tensor_by_name_from_graph(graph: Graph, tensor_name: str) Tensor[source]
Load tensor value from the given tf.Graph object.
- deepmd.utils.graph.get_tensor_by_type(node, data_type: dtype) Tensor[source]
Get the tensor value within the given node according to the input data_type.
- Parameters
- node
The given tensorflow graph node
- data_type
The data type of the node
- Returns
tf.TensorThe tensor value of the given node
- deepmd.utils.graph.get_type_embedding_net_nodes_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the type embedding net nodes with the given tf.GraphDef object.
- deepmd.utils.graph.get_type_embedding_net_variables_from_graph_def(graph_def: GraphDef, suffix: str = '') Dict[source]
Get the type embedding net variables with the given tf.GraphDef object.
- deepmd.utils.graph.get_variables_from_graph_def_as_numpy_array(graph_def: GraphDef, pattern: str)[source]
Get variables from the given tf.GraphDef object, with numpy array returns.
- Parameters
- graph_def
The input tf.GraphDef object
- pattern
str The name of variable
- Returns
np.ndarrayThe numpy array of the variable
deepmd.utils.learning_rate module
- class deepmd.utils.learning_rate.LearningRateExp(start_lr: float, stop_lr: float = 5e-08, decay_steps: int = 5000, decay_rate: float = 0.95)[source]
Bases:
objectThe exponentially decaying learning rate.
The learning rate at step \(t\) is given by
\[\alpha(t) = \alpha_0 \lambda ^ { t / \tau }\]where \(\alpha\) is the learning rate, \(\alpha_0\) is the starting learning rate, \(\lambda\) is the decay rate, and \(\tau\) is the decay steps.
- Parameters
- start_lr
Starting learning rate \(\alpha_0\)
- stop_lr
Stop learning rate \(\alpha_1\)
- decay_steps
Learning rate decay every this number of steps \(\tau\)
- decay_rate
The decay rate \(\lambda\). If stop_step is provided in build, then it will be determined automatically and overwritten.
Methods
build(global_step[, stop_step])Build the learning rate.
start_lr()Get the start lr.
value(step)Get the lr at a certain step.
- build(global_step: Tensor, stop_step: Optional[int] = None) Tensor[source]
Build the learning rate.
- Parameters
- global_step
The tf Tensor prividing the global training step
- stop_step
The stop step. If provided, the decay_rate will be determined automatically and overwritten.
- Returns
learning_rateThe learning rate
deepmd.utils.multi_init module
deepmd.utils.neighbor_stat module
- class deepmd.utils.neighbor_stat.NeighborStat(ntypes: int, rcut: float, one_type: bool = False)[source]
Bases:
objectClass for getting training data information.
It loads data from DeepmdData object, and measures the data info, including neareest nbor distance between atoms, max nbor size of atoms and the output data range of the environment matrix.
- Parameters
- ntypes
The num of atom types
- rcut
The cut-off radius
- one_typebool,
optional, default=False Treat all types as a single type.
Methods
build()Build the graph.
get_stat(data)Get the data statistics of the training data, including nearest nbor distance between atoms, max nbor size of atoms.
iterator(data)Produce data.
- get_stat(data: DeepmdDataSystem) Tuple[float, ndarray][source]
Get the data statistics of the training data, including nearest nbor distance between atoms, max nbor size of atoms.
- Parameters
- data
Class for manipulating many data systems. It is implemented with the help of DeepmdData.
- Returns
min_nbor_distThe nearest distance between neighbor atoms
max_nbor_sizeAn array with ntypes integers, denotes the actual achieved max sel
- class deepmd.utils.neighbor_stat.NeighborStatOP(ntypes: int, rcut: float, distinguish_types: bool)[source]
Bases:
objectClass for getting neighbor statics data information.
- Parameters
- ntypes
The num of atom types
- rcut
The cut-off radius
- distinguish_typesbool,
optional If False, treat all types as a single type.
Methods
build(coord, atype, cell, pbc)Calculate the nearest neighbor distance between atoms, maximum nbor size of atoms and the output data range of the environment matrix.
deepmd.utils.network module
- deepmd.utils.network.embedding_net(xx, network_size, precision, activation_fn=<function tanh>, resnet_dt=False, name_suffix='', stddev=1.0, bavg=0.0, seed=None, trainable=True, uniform_seed=False, initial_variables=None, mixed_prec=None)[source]
The embedding network.
The embedding network function \(\mathcal{N}\) is constructed by is the composition of multiple layers \(\mathcal{L}^{(i)}\):
\[\mathcal{N} = \mathcal{L}^{(n)} \circ \mathcal{L}^{(n-1)} \circ \cdots \circ \mathcal{L}^{(1)}\]A layer \(\mathcal{L}\) is given by one of the following forms, depending on the number of nodes: [1]
\[\begin{split}\mathbf{y}=\mathcal{L}(\mathbf{x};\mathbf{w},\mathbf{b})= \begin{cases} \boldsymbol{\phi}(\mathbf{x}^T\mathbf{w}+\mathbf{b}) + \mathbf{x}, & N_2=N_1 \\ \boldsymbol{\phi}(\mathbf{x}^T\mathbf{w}+\mathbf{b}) + (\mathbf{x}, \mathbf{x}), & N_2 = 2N_1\\ \boldsymbol{\phi}(\mathbf{x}^T\mathbf{w}+\mathbf{b}), & \text{otherwise} \\ \end{cases}\end{split}\]where \(\mathbf{x} \in \mathbb{R}^{N_1}\) is the input vector and \(\mathbf{y} \in \mathbb{R}^{N_2}\) is the output vector. \(\mathbf{w} \in \mathbb{R}^{N_1 \times N_2}\) and \(\mathbf{b} \in \mathbb{R}^{N_2}\) are weights and biases, respectively, both of which are trainable if trainable is True. \(\boldsymbol{\phi}\) is the activation function.
- Parameters
- xx
Tensor Input tensor \(\mathbf{x}\) of shape [-1,1]
- network_size
listofint Size of the embedding network. For example [16,32,64]
- precision:
Precision of network weights. For example, tf.float64
- activation_fn:
Activation function \(\boldsymbol{\phi}\)
- resnet_dtbool
Using time-step in the ResNet construction
- name_suffix
str The name suffix append to each variable.
- stddev
float Standard deviation of initializing network parameters
- bavg
float Mean of network intial bias
- seed
int Random seed for initializing network parameters
- trainablebool
If the network is trainable
- uniform_seedbool
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- initial_variables
dict The input dict which stores the embedding net variables
- mixed_prec
The input dict which stores the mixed precision setting for the embedding net
- xx
References
- deepmd.utils.network.one_layer(inputs, outputs_size, activation_fn=<function tanh>, precision=tf.float64, stddev=1.0, bavg=0.0, name='linear', scope='', reuse=None, seed=None, use_timestep=False, trainable=True, useBN=False, uniform_seed=False, initial_variables=None, mixed_prec=None, final_layer=False)[source]
- deepmd.utils.network.variable_summaries(var: VariableV1, name: str)[source]
Attach a lot of summaries to a Tensor (for TensorBoard visualization).
- Parameters
- var
tf.Variable [description]
- name
str variable name
- var
deepmd.utils.nlist module
deepmd.utils.pair_tab module
Alias for backward compatibility.
- class deepmd.utils.pair_tab.PairTab(filename: str)[source]
Bases:
objectPairwise tabulated potential.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
Methods
get()Get the serialized table.
reinit(filename)Initialize the tabulated interaction.
- reinit(filename: str) None[source]
Initialize the tabulated interaction.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
deepmd.utils.parallel_op module
- class deepmd.utils.parallel_op.ParallelOp(builder: Callable[[...], Tuple[Dict[str, Tensor], Tuple[Tensor]]], nthreads: Optional[int] = None, config: Optional[ConfigProto] = None)[source]
Bases:
objectRun an op with data parallelism.
- Parameters
Examples
>>> from deepmd.env import tf >>> from deepmd.utils.parallel_op import ParallelOp >>> def builder(): ... x = tf.placeholder(tf.int32, [1]) ... return {"x": x}, (x + 1) ... >>> p = ParallelOp(builder, nthreads=4) >>> def feed(): ... for ii in range(10): ... yield {"x": [ii]} ... >>> print(*p.generate(tf.Session(), feed())) [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]
Methods
generate(sess, feed)Returns a generator.
deepmd.utils.path module
Alias for backward compatibility.
- class deepmd.utils.path.DPH5Path(path: str)[source]
Bases:
DPPathThe path class to data system (DeepmdData) for HDF5 files.
- Parameters
- path
str path
- path
Notes
- OS - HDF5 relationship:
directory - Group file - Dataset
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt([dtype])Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- class deepmd.utils.path.DPOSPath(path: str)[source]
Bases:
DPPathThe OS path class to data system (DeepmdData) for real directories.
- Parameters
- path
str path
- path
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt(**kwargs)Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- load_txt(**kwargs) ndarray[source]
Load NumPy array from text.
- Returns
np.ndarrayloaded NumPy array
- class deepmd.utils.path.DPPath(path: str)[source]
Bases:
ABCThe path class to data system (DeepmdData).
- Parameters
- path
str path
- path
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt(**kwargs)Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- abstract load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- abstract load_txt(**kwargs) ndarray[source]
Load NumPy array from text.
- Returns
np.ndarrayloaded NumPy array
deepmd.utils.plugin module
Alias for backward compatibility.
- class deepmd.utils.plugin.Plugin[source]
Bases:
objectA class to register and restore plugins.
Examples
>>> plugin = Plugin() >>> @plugin.register("xx") def xxx(): pass >>> print(plugin.plugins['xx'])
Methods
get_plugin(key)Visit a plugin by key.
register(key)Register a plugin.
- class deepmd.utils.plugin.PluginVariant(*args, **kwargs)[source]
Bases:
objectA class to remove type from input arguments.
- class deepmd.utils.plugin.VariantABCMeta(name, bases, namespace, **kwargs)[source]
Bases:
VariantMeta,ABCMetaMethods
__call__(*args, **kwargs)Remove type and keys that starts with underline.
mro(/)Return a type's method resolution order.
register(subclass)Register a virtual subclass of an ABC.
deepmd.utils.random module
Alias for backward compatibility.
- deepmd.utils.random.choice(a: ndarray, p: Optional[ndarray] = None)[source]
Generates a random sample from a given 1-D array.
- Parameters
- a
np.ndarray A random sample is generated from its elements.
- p
np.ndarray The probabilities associated with each entry in a.
- a
- Returns
np.ndarrayarrays with results and their shapes
- deepmd.utils.random.random(size=None)[source]
Return random floats in the half-open interval [0.0, 1.0).
- Parameters
- size
Output shape.
- Returns
np.ndarrayArrays with results and their shapes.
- deepmd.utils.random.seed(val: Optional[int] = None)[source]
Seed the generator.
- Parameters
- val
int Seed.
- val
- deepmd.utils.random.shuffle(x: ndarray)[source]
Modify a sequence in-place by shuffling its contents.
- Parameters
- x
np.ndarray The array or list to be shuffled.
- x
deepmd.utils.region module
deepmd.utils.sess module
deepmd.utils.spin module
- class deepmd.utils.spin.Spin(use_spin: Optional[List[bool]] = None, spin_norm: Optional[List[float]] = None, virtual_len: Optional[List[float]] = None)[source]
Bases:
objectClass for spin.
- Parameters
- use_spin
Whether to use atomic spin model for each atom type
- spin_norm
The magnitude of atomic spin for each atom type with spin
- virtual_len
The distance between virtual atom representing spin and its corresponding real atom for each atom type with spin
Methods
build([reuse, suffix])Build the computational graph for the spin.
Returns the number of atom types which contain spin.
Returns the list of magnitude of atomic spin for each atom type.
Returns the list of whether to use spin for each atom type.
Returns the list of distance between real atom and virtual atom for each atom type.
- build(reuse=None, suffix='')[source]
Build the computational graph for the spin.
- Parameters
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
embedded_typesThe computational graph for embedded types
deepmd.utils.tabulate module
- class deepmd.utils.tabulate.DPTabulate(descrpt: ~deepmd.descriptor.descriptor.Descriptor, neuron: ~typing.List[int], graph: ~tensorflow.python.framework.ops.Graph, graph_def: ~tensorflow.core.framework.graph_pb2.GraphDef, type_one_side: bool = False, exclude_types: ~typing.List[~typing.List[int]] = [], activation_fn: ~typing.Callable[[~tensorflow.python.framework.tensor.Tensor], ~tensorflow.python.framework.tensor.Tensor] = <function tanh>, suffix: str = '')[source]
Bases:
objectClass for tabulation.
Compress a model, which including tabulating the embedding-net. The table is composed of fifth-order polynomial coefficients and is assembled from two sub-tables. The first table takes the stride(parameter) as it’s uniform stride, while the second table takes 10 * stride as it’s uniform stride The range of the first table is automatically detected by deepmd-kit, while the second table ranges from the first table’s upper boundary(upper) to the extrapolate(parameter) * upper.
- Parameters
- descrpt
Descriptor of the original model
- neuron
Number of neurons in each hidden layers of the embedding net \(\\mathcal{N}\)
- graph
tf.Graph The graph of the original model
- graph_def
tf.GraphDef The graph_def of the original model
- type_one_side
Try to build N_types tables. Otherwise, building N_types^2 tables
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- activation_function
The activation function in the embedding net. Supported options are {“tanh”,”gelu”} in common.ACTIVATION_FN_DICT.
- suffix
str,optional The suffix of the scope
Methods
build(min_nbor_dist, extrapolate, stride0, ...)Build the tables for model compression.
- build(min_nbor_dist: float, extrapolate: float, stride0: float, stride1: float) Tuple[Dict[str, int], Dict[str, int]][source]
Build the tables for model compression.
- Parameters
- min_nbor_dist
The nearest distance between neighbor atoms
- extrapolate
The scale of model extrapolation
- stride0
The uniform stride of the first table
- stride1
The uniform stride of the second table
- Returns
deepmd.utils.type_embed module
- class deepmd.utils.type_embed.TypeEmbedNet(neuron: List[int] = [], resnet_dt: bool = False, activation_function: Optional[str] = 'tanh', precision: str = 'default', trainable: bool = True, seed: Optional[int] = None, uniform_seed: bool = False, padding: bool = False, **kwargs)[source]
Bases:
objectType embedding network.
- Parameters
- neuron
list[int] Number of neurons in each hidden layers of the embedding net
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- trainable
If the weights of embedding net are trainable.
- seed
Random seed for initializing the network parameters.
- uniform_seed
Only for the purpose of backward compatibility, retrieves the old behavior of using the random seed
- padding
Concat the zero padding to the output, as the default embedding of empty type.
- neuron
Methods
build(ntypes[, reuse, suffix])Build the computational graph for the descriptor.
init_variables(graph, graph_def[, suffix, ...])Init the type embedding net variables with the given dict.
- build(ntypes: int, reuse=None, suffix='')[source]
Build the computational graph for the descriptor.
- Parameters
- ntypes
Number of atom types.
- reuse
The weights in the networks should be reused when get the variable.
- suffix
Name suffix to identify this descriptor
- Returns
embedded_typesThe computational graph for embedded types
- init_variables(graph: Graph, graph_def: GraphDef, suffix='', model_type='original_model') None[source]
Init the type embedding net variables with the given dict.
- Parameters
- graph
tf.Graph The input frozen model graph
- graph_def
tf.GraphDef The input frozen model graph_def
- suffix
Name suffix to identify this descriptor
- model_type
Indicator of whether this model is a compressed model
- graph
- deepmd.utils.type_embed.embed_atom_type(ntypes: int, natoms: Tensor, type_embedding: Tensor)[source]
Make the embedded type for the atoms in system. The atoms are assumed to be sorted according to the type, thus their types are described by a tf.Tensor natoms, see explanation below.
- Parameters
- ntypes:
Number of types.
- natoms:
The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- type_embedding:
The type embedding. It has the shape of [ntypes, embedding_dim]
- Returns
atom_embeddingThe embedded type of each atom. It has the shape of [numb_atoms, embedding_dim]
deepmd.utils.weight_avg module
Alias for backward compatibility.
Submodules
deepmd.calculator module
ASE calculator interface module.
- class deepmd.calculator.DP(model: Union[str, Path], label: str = 'DP', type_dict: Optional[Dict[str, int]] = None, neighbor_list=None, **kwargs)[source]
Bases:
CalculatorImplementation of ASE deepmd calculator.
Implemented propertie are energy, forces and stress
- Parameters
- model
Union[str,Path] path to the model
- label
str,optional calculator label, by default “DP”
- type_dict
Dict[str,int],optional mapping of element types and their numbers, best left None and the calculator will infer this information from model, by default None
- neighbor_list
ase.neighborlist.NeighborList,optional The neighbor list object. If None, then build the native neighbor list.
- model
Examples
Compute potential energy
>>> from ase import Atoms >>> from deepmd.calculator import DP >>> water = Atoms('H2O', >>> positions=[(0.7601, 1.9270, 1), >>> (1.9575, 1, 1), >>> (1., 1., 1.)], >>> cell=[100, 100, 100], >>> calculator=DP(model="frozen_model.pb")) >>> print(water.get_potential_energy()) >>> print(water.get_forces())
Run BFGS structure optimization
>>> from ase.optimize import BFGS >>> dyn = BFGS(water) >>> dyn.run(fmax=1e-6) >>> print(water.get_positions())
- Attributes
- directory
- label
Methods
band_structure()Create band-structure object for plotting.
calculate([atoms, properties, system_changes])Run calculation with deepmd model.
calculate_numerical_forces(atoms[, d])Calculate numerical forces using finite difference.
calculate_numerical_stress(atoms[, d, voigt])Calculate numerical stress using finite difference.
calculate_properties(atoms, properties)This method is experimental; currently for internal use.
check_state(atoms[, tol])Check for any system changes since last calculation.
get_magnetic_moments([atoms])Calculate magnetic moments projected onto atoms.
get_property(name[, atoms, allow_calculation])Get the named property.
get_stresses([atoms])the calculator should return intensive stresses, i.e., such that stresses.sum(axis=0) == stress
read(label)Read atoms, parameters and calculated properties from output file.
reset()Clear all information from old calculation.
set(**kwargs)Set parameters like set(key1=value1, key2=value2, ...).
set_label(label)Set label and convert label to directory and prefix.
calculation_required
export_properties
get_atoms
get_charges
get_default_parameters
get_dipole_moment
get_forces
get_magnetic_moment
get_potential_energies
get_potential_energy
get_stress
read_atoms
todict
- calculate(atoms: Optional[Atoms] = None, properties: List[str] = ['energy', 'forces', 'virial'], system_changes: List[str] = ['positions', 'numbers', 'cell', 'pbc', 'initial_charges', 'initial_magmoms'])[source]
Run calculation with deepmd model.
- Parameters
- atoms
Optional[Atoms],optional atoms object to run the calculation on, by default None
- properties
List[str],optional unused, only for function signature compatibility, by default [“energy”, “forces”, “stress”]
- system_changes
List[str],optional unused, only for function signature compatibility, by default all_changes
- atoms
- implemented_properties: ClassVar[List[str]] = ['energy', 'free_energy', 'forces', 'virial', 'stress']
Properties calculator can handle (energy, forces, …)
- name = 'DP'
deepmd.common module
Collection of functions and classes used throughout the whole package.
- deepmd.common.add_data_requirement(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[bool] = None, repeat: int = 1, default: float = 0.0, dtype: Optional[dtype] = None)[source]
Specify data requirements for training.
- Parameters
- key
str type of data stored in corresponding *.npy file e.g. forces or energy
- ndof
int number of the degrees of freedom, this is tied to atomic parameter e.g. forces have atomic=True and ndof=3
- atomicbool,
optional specifies whwther the ndof keyworrd applies to per atom quantity or not, by default False
- mustbool,
optional specifi if the *.npy data file must exist, by default False
- high_precbool,
optional if true load data to np.float64 else np.float32, by default False
- type_selbool,
optional select only certain type of atoms, by default None
- repeat
int,optional if specify repaeat data repeat times, by default 1
- default
float,optional, default=0. default value of data
- dtype
np.dtype,optional the dtype of data, overwrites high_prec if provided
- key
- deepmd.common.cast_precision(func: Callable) Callable[source]
A decorator that casts and casts back the input and output tensor of a method.
The decorator should be used in a classmethod.
The decorator will do the following thing: (1) It casts input Tensors from GLOBAL_TF_FLOAT_PRECISION to precision defined by property precision. (2) It casts output Tensors from precision to GLOBAL_TF_FLOAT_PRECISION. (3) It checks inputs and outputs and only casts when input or output is a Tensor and its dtype matches GLOBAL_TF_FLOAT_PRECISION and precision, respectively. If it does not match (e.g. it is an integer), the decorator will do nothing on it.
- Returns
Callablea decorator that casts and casts back the input and output tensor of a method
Examples
>>> class A: ... @property ... def precision(self): ... return tf.float32 ... ... @cast_precision ... def f(x: tf.Tensor, y: tf.Tensor) -> tf.Tensor: ... return x ** 2 + y
- deepmd.common.expand_sys_str(root_dir: Union[str, Path]) List[str][source]
Recursively iterate over directories taking those that contain type.raw file.
- deepmd.common.gelu(x: Tensor) Tensor[source]
Gaussian Error Linear Unit.
This is a smoother version of the RELU, implemented by custom operator.
- Parameters
- x
tf.Tensor float Tensor to perform activation
- x
- Returns
tf.Tensorx with the GELU activation applied
References
Original paper https://arxiv.org/abs/1606.08415
- deepmd.common.gelu_tf(x: Tensor) Tensor[source]
Gaussian Error Linear Unit.
This is a smoother version of the RELU, implemented by TF.
- Parameters
- x
tf.Tensor float Tensor to perform activation
- x
- Returns
tf.Tensorx with the GELU activation applied
References
Original paper https://arxiv.org/abs/1606.08415
- deepmd.common.get_activation_func(activation_fn: Optional[_ACTIVATION]) Optional[Callable[[Tensor], Tensor]][source]
Get activation function callable based on string name.
- Parameters
- activation_fn
_ACTIVATION one of the defined activation functions
- activation_fn
- Returns
- Raises
RuntimeErrorif unknown activation function is specified
- deepmd.common.get_np_precision(precision: _PRECISION) dtype[source]
Get numpy precision constant from string.
- Parameters
- precision
_PRECISION string name of numpy constant or default
- precision
- Returns
np.dtypenumpy presicion constant
- Raises
RuntimeErrorif string is invalid
- deepmd.common.get_precision(precision: _PRECISION) Any[source]
Convert str to TF DType constant.
- Parameters
- precision
_PRECISION one of the allowed precisions
- precision
- Returns
tf.python.framework.dtypes.DTypeappropriate TF constant
- Raises
RuntimeErrorif supplied precision string does not have acorresponding TF constant
- deepmd.common.j_loader(filename: Union[str, Path]) Dict[str, Any][source]
Load yaml or json settings file.
- deepmd.common.j_must_have(jdata: Dict[str, _DICT_VAL], key: str, deprecated_key: List[str] = []) _DICT_VAL[source]
Assert that supplied dictionary conaines specified key.
- Returns
_DICT_VALvalue that was store unde supplied key
- Raises
RuntimeErrorif the key is not present
- deepmd.common.make_default_mesh(pbc: bool, mixed_type: bool) ndarray[source]
Make mesh.
Only the size of mesh matters, not the values: * 6 for PBC, no mixed types * 0 for no PBC, no mixed types * 7 for PBC, mixed types * 1 for no PBC, mixed types
- Parameters
- Returns
np.ndarraymesh
- deepmd.common.safe_cast_tensor(input: Tensor, from_precision: DType, to_precision: DType) Tensor[source]
Convert a Tensor from a precision to another precision.
If input is not a Tensor or without the specific precision, the method will not cast it.
- deepmd.common.select_idx_map(atom_types: ndarray, select_types: ndarray) ndarray[source]
Build map of indices for element supplied element types from all atoms list.
- Parameters
- atom_types
np.ndarray array specifing type for each atoms as integer
- select_types
np.ndarray types of atoms you want to find indices for
- atom_types
- Returns
np.ndarrayindices of types of atoms defined by select_types in atom_types array
Warning
select_types array will be sorted before finding indices in atom_types
deepmd.env module
Module that sets tensorflow working environment and exports inportant constants.
- deepmd.env.GLOBAL_ENER_FLOAT_PRECISION
alias of
float64
- deepmd.env.GLOBAL_NP_FLOAT_PRECISION
alias of
float64
- deepmd.env.global_cvt_2_ener_float(xx: Tensor) Tensor[source]
Cast tensor to globally set energy precision.
deepmd.lmp module
Register entry points for lammps-wheel.
- deepmd.lmp.get_env(paths: List[Optional[str]]) str[source]
Get the environment variable from given paths.
deepmd_utils package
Untilization methods for DeePMD-kit.
The __init__ module should not import any modules for performance.
Subpackages
deepmd_utils.entrypoints package
Submodules
deepmd_utils.entrypoints.doc module
Module that prints train input arguments docstrings.
deepmd_utils.entrypoints.gui module
DP-GUI entrypoint.
- deepmd_utils.entrypoints.gui.start_dpgui(*, port: int, bind_all: bool, **kwargs)[source]
Host DP-GUI server.
- Parameters
- Raises
ModuleNotFoundErrorThe dpgui package is not installed
deepmd_utils.loggers package
Module taking care of logging duties.
- deepmd_utils.loggers.set_log_handles(level: int, log_path: Optional[Path] = None, mpi_log: Optional[str] = None)[source]
Set desired level for package loggers and add file handlers.
- Parameters
- level
int logging level
- log_path
Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None
- mpi_log
Optional[str],optional mpi log type. Has three options. master will output logs to file and console only from rank==0. collect will write messages from all ranks to one file opened under rank==0 and to console. workers will open one log file for each worker designated by its rank, console behaviour is the same as for collect. If this argument is specified, package ‘mpi4py’ must be already installed. by default None
- level
- Raises
RuntimeErrorIf the argument mpi_log is specified, package mpi4py is not installed.
Notes
Logging levels:
our notation
python logging
tensorflow cpp
OpenMP
debug
10
10
0
1/on/true/yes
info
20
20
1
0/off/false/no
warning
30
30
2
0/off/false/no
error
40
40
3
0/off/false/no
References
https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu
Submodules
deepmd_utils.loggers.loggers module
Logger initialization for package.
- deepmd_utils.loggers.loggers.set_log_handles(level: int, log_path: Optional[Path] = None, mpi_log: Optional[str] = None)[source]
Set desired level for package loggers and add file handlers.
- Parameters
- level
int logging level
- log_path
Optional[str] path to log file, if None logs will be send only to console. If the parent directory does not exist it will be automatically created, by default None
- mpi_log
Optional[str],optional mpi log type. Has three options. master will output logs to file and console only from rank==0. collect will write messages from all ranks to one file opened under rank==0 and to console. workers will open one log file for each worker designated by its rank, console behaviour is the same as for collect. If this argument is specified, package ‘mpi4py’ must be already installed. by default None
- level
- Raises
RuntimeErrorIf the argument mpi_log is specified, package mpi4py is not installed.
Notes
Logging levels:
our notation
python logging
tensorflow cpp
OpenMP
debug
10
10
0
1/on/true/yes
info
20
20
1
0/off/false/no
warning
30
30
2
0/off/false/no
error
40
40
3
0/off/false/no
References
https://groups.google.com/g/mpi4py/c/SaNzc8bdj6U https://stackoverflow.com/questions/35869137/avoid-tensorflow-print-on-standard-error https://stackoverflow.com/questions/56085015/suppress-openmp-debug-messages-when-running-tensorflow-on-cpu
deepmd_utils.model_format package
- class deepmd_utils.model_format.DescrptSeA(rcut: float, rcut_smth: float, sel: List[int], neuron: List[int] = [24, 48, 96], axis_neuron: int = 8, resnet_dt: bool = False, trainable: bool = True, type_one_side: bool = True, exclude_types: List[List[int]] = [], set_davg_zero: bool = False, activation_function: str = 'tanh', precision: str = 'float64', spin: Optional[Any] = None)[source]
Bases:
NativeOPDeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net().- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- multi_task
If the model has multi fitting nets to train.
- spin
The deepspin object.
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
Methods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(coord_ext, atype_ext, nlist)Compute the descriptor.
cal_g
deserialize
serialize
- call(coord_ext, atype_ext, nlist)[source]
Compute the descriptor.
- Parameters
- coord_ext
The extended coordinates of atoms. shape: nf x (nallx3)
- atype_ext
The extended aotm types. shape: nf x nall
- nlist
The neighbor list. shape: nf x nloc x nnei
- Returns
descriptorThe descriptor. shape: nf x nloc x ng x axis_neuron
- classmethod deserialize(data: dict) DescrptSeA[source]
- deepmd_utils.model_format.EmbeddingNet
alias of
EN
- class deepmd_utils.model_format.EnvMat(rcut, rcut_smth)[source]
Bases:
NativeOPMethods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(coord_ext, atype_ext, nlist[, davg, dstd])Compute the environment matrix.
deserialize
serialize
- call(coord_ext: ndarray, atype_ext: ndarray, nlist: ndarray, davg: Optional[ndarray] = None, dstd: Optional[ndarray] = None) ndarray[source]
Compute the environment matrix.
- Parameters
- nlist
The neighbor list. shape: nf x nloc x nnei
- coord_ext
The extended coordinates of atoms. shape: nf x (nallx3)
- atype_ext
The extended aotm types. shape: nf x nall
- davg
The data avg. shape: nt x nnei x 4
- dstd
The inverse of data std. shape: nt x nnei x 4
- Returns
env_matThe environment matrix. shape: nf x nloc x nnei x 4
switchThe value of switch function. shape: nf x nloc x nnei
- deepmd_utils.model_format.FittingNet
alias of
FN
- class deepmd_utils.model_format.FittingOutputDef(var_defs: List[OutputVariableDef])[source]
Bases:
objectDefines the shapes and other properties of the fitting network outputs.
It is assume that the fitting network output variables for each local atom. This class defines all the outputs.
- Parameters
- var_defs
List of output variable definitions.
Methods
get_data
keys
- get_data() Dict[str, OutputVariableDef][source]
- class deepmd_utils.model_format.ModelOutputDef(fit_defs: FittingOutputDef)[source]
Bases:
objectDefines the shapes and other properties of the model outputs.
The model reduce and differentiate fitting outputs if applicable. If a variable is named by foo, then the reduced variable is called foo_redu, the derivative w.r.t. coordinates is called foo_derv_r and the derivative w.r.t. cell is called foo_derv_c.
- Parameters
- fit_defs
Definition for the fitting net output
Methods
get_data
keys
keys_derv_c
keys_derv_r
keys_outp
keys_redu
- class deepmd_utils.model_format.NativeLayer(num_in, num_out, bias: bool = True, use_timestep: bool = False, activation_function: Optional[str] = None, resnet: bool = False, precision: str = 'float64')[source]
Bases:
NativeOPNative representation of a layer.
- Parameters
- w
np.ndarray,optional The weights of the layer.
- b
np.ndarray,optional The biases of the layer.
- idt
np.ndarray,optional The identity matrix of the layer.
- activation_function
str,optional The activation function of the layer.
- resnetbool,
optional Whether the layer is a residual layer.
- w
Methods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(x)Forward pass.
deserialize(data)Deserialize the layer from a dict.
Serialize the layer to a dict.
check_shape_consistency
check_type_consistency
dim_in
dim_out
- call(x: ndarray) ndarray[source]
Forward pass.
- Parameters
- x
np.ndarray The input.
- x
- Returns
np.ndarrayThe output.
- classmethod deserialize(data: dict) NativeLayer[source]
Deserialize the layer from a dict.
- Parameters
- data
dict The dict to deserialize from.
- data
- deepmd_utils.model_format.NativeNet
alias of
NN
- class deepmd_utils.model_format.NativeOP[source]
Bases:
ABCThe unit operation of a native model.
Methods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(*args, **kwargs)Forward pass in NumPy implementation.
- class deepmd_utils.model_format.NetworkCollection(ndim: int, ntypes: int, network_type: str = 'network', networks: ~typing.List[~typing.Union[~deepmd_utils.model_format.network.make_multilayer_network.<locals>.NN, dict]] = [])[source]
Bases:
objectA collection of networks for multiple elements.
The number of dimesions for types might be 0, 1, or 2. - 0: embedding or fitting with type embedding, in () - 1: embedding with type_one_side, or fitting, in (type_i) - 2: embedding without type_one_side, in (type_i, type_j)
- Parameters
Methods
Check whether the collection is complete.
deserialize(data)Deserialize the networks from a dict.
Serialize the networks to a dict.
- NETWORK_TYPE_MAP: ClassVar[Dict[str, type]] = {'embedding_network': <class 'deepmd_utils.model_format.network.make_embedding_network.<locals>.EN'>, 'fitting_network': <class 'deepmd_utils.model_format.network.make_fitting_network.<locals>.FN'>, 'network': <class 'deepmd_utils.model_format.network.make_multilayer_network.<locals>.NN'>}
- check_completeness()[source]
Check whether the collection is complete.
- Raises
RuntimeErrorIf the collection is incomplete.
- classmethod deserialize(data: dict) NetworkCollection[source]
Deserialize the networks from a dict.
- Parameters
- data
dict The dict to deserialize from.
- data
- class deepmd_utils.model_format.OutputVariableDef(name: str, shape: List[int], reduciable: bool = False, differentiable: bool = False, atomic: bool = True)[source]
Bases:
objectDefines the shape and other properties of the one output variable.
It is assume that the fitting network output variables for each local atom. This class defines one output variable, including its name, shape, reducibility and differentiability.
- Parameters
- name
Name of the output variable. Notice that the xxxx_redu, xxxx_derv_c, xxxx_derv_r are reserved names that should not be used to define variables.
- shape
The shape of the variable. e.g. energy should be [1], dipole should be [3], polarizabilty should be [3,3].
- reduciable
If the variable is reduced.
- differentiable
If the variable is differentiated with respect to coordinates of atoms and cell tensor (pbc case). Only reduciable variable are differentiable.
- deepmd_utils.model_format.fitting_check_output(cls)[source]
Check if the output of the Fitting is consistent with the definition.
Two methods are assumed to be provided by the Fitting: 1. Fitting.output_def that gives the output definition. 2. Fitting.__call__ defines the forward path of the fitting.
- deepmd_utils.model_format.load_dp_model(filename: str) dict[source]
Load a DP model from a file in the native format.
- deepmd_utils.model_format.model_check_output(cls)[source]
Check if the output of the Model is consistent with the definition.
Two methods are assumed to be provided by the Model: 1. Model.output_def that gives the output definition. 2. Model.__call__ that defines the forward path of the model.
- deepmd_utils.model_format.save_dp_model(filename: str, model_dict: dict, extra_info: Optional[dict] = None)[source]
Save a DP model to a file in the native format.
- deepmd_utils.model_format.traverse_model_dict(model_obj, callback: callable, is_variable: bool = False)[source]
Traverse a model dict and call callback on each variable.
- Parameters
- model_obj
object The model object to traverse.
- callback
callable() The callback function to call on each variable.
- is_variablebool,
optional Whether the current node is a variable.
- model_obj
- Returns
objectThe model object after traversing.
Submodules
deepmd_utils.model_format.common module
deepmd_utils.model_format.env_mat module
- class deepmd_utils.model_format.env_mat.EnvMat(rcut, rcut_smth)[source]
Bases:
NativeOPMethods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(coord_ext, atype_ext, nlist[, davg, dstd])Compute the environment matrix.
deserialize
serialize
- call(coord_ext: ndarray, atype_ext: ndarray, nlist: ndarray, davg: Optional[ndarray] = None, dstd: Optional[ndarray] = None) ndarray[source]
Compute the environment matrix.
- Parameters
- nlist
The neighbor list. shape: nf x nloc x nnei
- coord_ext
The extended coordinates of atoms. shape: nf x (nallx3)
- atype_ext
The extended aotm types. shape: nf x nall
- davg
The data avg. shape: nt x nnei x 4
- dstd
The inverse of data std. shape: nt x nnei x 4
- Returns
env_matThe environment matrix. shape: nf x nloc x nnei x 4
switchThe value of switch function. shape: nf x nloc x nnei
deepmd_utils.model_format.network module
Native DP model format for multiple backends.
See issue #2982 for more information.
- class deepmd_utils.model_format.network.Counter[source]
Bases:
objectA callable counter.
Examples
>>> counter = Counter() >>> counter() 0 >>> counter() 1
Methods
__call__()Call self as a function.
- deepmd_utils.model_format.network.EmbeddingNet
alias of
EN
- deepmd_utils.model_format.network.FittingNet
alias of
FN
- class deepmd_utils.model_format.network.NativeLayer(num_in, num_out, bias: bool = True, use_timestep: bool = False, activation_function: Optional[str] = None, resnet: bool = False, precision: str = 'float64')[source]
Bases:
NativeOPNative representation of a layer.
- Parameters
- w
np.ndarray,optional The weights of the layer.
- b
np.ndarray,optional The biases of the layer.
- idt
np.ndarray,optional The identity matrix of the layer.
- activation_function
str,optional The activation function of the layer.
- resnetbool,
optional Whether the layer is a residual layer.
- w
Methods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(x)Forward pass.
deserialize(data)Deserialize the layer from a dict.
Serialize the layer to a dict.
check_shape_consistency
check_type_consistency
dim_in
dim_out
- call(x: ndarray) ndarray[source]
Forward pass.
- Parameters
- x
np.ndarray The input.
- x
- Returns
np.ndarrayThe output.
- classmethod deserialize(data: dict) NativeLayer[source]
Deserialize the layer from a dict.
- Parameters
- data
dict The dict to deserialize from.
- data
- deepmd_utils.model_format.network.NativeNet
alias of
NN
- class deepmd_utils.model_format.network.NetworkCollection(ndim: int, ntypes: int, network_type: str = 'network', networks: ~typing.List[~typing.Union[~deepmd_utils.model_format.network.make_multilayer_network.<locals>.NN, dict]] = [])[source]
Bases:
objectA collection of networks for multiple elements.
The number of dimesions for types might be 0, 1, or 2. - 0: embedding or fitting with type embedding, in () - 1: embedding with type_one_side, or fitting, in (type_i) - 2: embedding without type_one_side, in (type_i, type_j)
- Parameters
Methods
Check whether the collection is complete.
deserialize(data)Deserialize the networks from a dict.
Serialize the networks to a dict.
- NETWORK_TYPE_MAP: ClassVar[Dict[str, type]] = {'embedding_network': <class 'deepmd_utils.model_format.network.make_embedding_network.<locals>.EN'>, 'fitting_network': <class 'deepmd_utils.model_format.network.make_fitting_network.<locals>.FN'>, 'network': <class 'deepmd_utils.model_format.network.make_multilayer_network.<locals>.NN'>}
- check_completeness()[source]
Check whether the collection is complete.
- Raises
RuntimeErrorIf the collection is incomplete.
- classmethod deserialize(data: dict) NetworkCollection[source]
Deserialize the networks from a dict.
- Parameters
- data
dict The dict to deserialize from.
- data
- deepmd_utils.model_format.network.load_dp_model(filename: str) dict[source]
Load a DP model from a file in the native format.
- deepmd_utils.model_format.network.make_fitting_network(T_EmbeddingNet, T_Network, T_NetworkLayer)[source]
- deepmd_utils.model_format.network.save_dp_model(filename: str, model_dict: dict, extra_info: Optional[dict] = None)[source]
Save a DP model to a file in the native format.
- deepmd_utils.model_format.network.traverse_model_dict(model_obj, callback: callable, is_variable: bool = False)[source]
Traverse a model dict and call callback on each variable.
- Parameters
- model_obj
object The model object to traverse.
- callback
callable() The callback function to call on each variable.
- is_variablebool,
optional Whether the current node is a variable.
- model_obj
- Returns
objectThe model object after traversing.
deepmd_utils.model_format.output_def module
- class deepmd_utils.model_format.output_def.FittingOutputDef(var_defs: List[OutputVariableDef])[source]
Bases:
objectDefines the shapes and other properties of the fitting network outputs.
It is assume that the fitting network output variables for each local atom. This class defines all the outputs.
- Parameters
- var_defs
List of output variable definitions.
Methods
get_data
keys
- get_data() Dict[str, OutputVariableDef][source]
- class deepmd_utils.model_format.output_def.ModelOutputDef(fit_defs: FittingOutputDef)[source]
Bases:
objectDefines the shapes and other properties of the model outputs.
The model reduce and differentiate fitting outputs if applicable. If a variable is named by foo, then the reduced variable is called foo_redu, the derivative w.r.t. coordinates is called foo_derv_r and the derivative w.r.t. cell is called foo_derv_c.
- Parameters
- fit_defs
Definition for the fitting net output
Methods
get_data
keys
keys_derv_c
keys_derv_r
keys_outp
keys_redu
- class deepmd_utils.model_format.output_def.OutputVariableDef(name: str, shape: List[int], reduciable: bool = False, differentiable: bool = False, atomic: bool = True)[source]
Bases:
objectDefines the shape and other properties of the one output variable.
It is assume that the fitting network output variables for each local atom. This class defines one output variable, including its name, shape, reducibility and differentiability.
- Parameters
- name
Name of the output variable. Notice that the xxxx_redu, xxxx_derv_c, xxxx_derv_r are reserved names that should not be used to define variables.
- shape
The shape of the variable. e.g. energy should be [1], dipole should be [3], polarizabilty should be [3,3].
- reduciable
If the variable is reduced.
- differentiable
If the variable is differentiated with respect to coordinates of atoms and cell tensor (pbc case). Only reduciable variable are differentiable.
- deepmd_utils.model_format.output_def.check_shape(shape: List[int], def_shape: List[int])[source]
Check if the shape satisfies the defined shape.
- deepmd_utils.model_format.output_def.do_derivative(def_outp: FittingOutputDef) Tuple[Dict[str, OutputVariableDef], Dict[str, OutputVariableDef]][source]
- deepmd_utils.model_format.output_def.do_reduce(def_outp: FittingOutputDef) Dict[str, OutputVariableDef][source]
- deepmd_utils.model_format.output_def.fitting_check_output(cls)[source]
Check if the output of the Fitting is consistent with the definition.
Two methods are assumed to be provided by the Fitting: 1. Fitting.output_def that gives the output definition. 2. Fitting.__call__ defines the forward path of the fitting.
- deepmd_utils.model_format.output_def.model_check_output(cls)[source]
Check if the output of the Model is consistent with the definition.
Two methods are assumed to be provided by the Model: 1. Model.output_def that gives the output definition. 2. Model.__call__ that defines the forward path of the model.
deepmd_utils.model_format.se_e2_a module
- class deepmd_utils.model_format.se_e2_a.DescrptSeA(rcut: float, rcut_smth: float, sel: List[int], neuron: List[int] = [24, 48, 96], axis_neuron: int = 8, resnet_dt: bool = False, trainable: bool = True, type_one_side: bool = True, exclude_types: List[List[int]] = [], set_davg_zero: bool = False, activation_function: str = 'tanh', precision: str = 'float64', spin: Optional[Any] = None)[source]
Bases:
NativeOPDeepPot-SE constructed from all information (both angular and radial) of atomic configurations. The embedding takes the distance between atoms as input.
The descriptor \(\mathcal{D}^i \in \mathcal{R}^{M_1 \times M_2}\) is given by [1]
\[\mathcal{D}^i = (\mathcal{G}^i)^T \mathcal{R}^i (\mathcal{R}^i)^T \mathcal{G}^i_<\]where \(\mathcal{R}^i \in \mathbb{R}^{N \times 4}\) is the coordinate matrix, and each row of \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]where \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Each row of the embedding matrix \(\mathcal{G}^i \in \mathbb{R}^{N \times M_1}\) consists of outputs of a embedding network \(\mathcal{N}\) of \(s(r_{ji})\):
\[(\mathcal{G}^i)_j = \mathcal{N}(s(r_{ji}))\]\(\mathcal{G}^i_< \in \mathbb{R}^{N \times M_2}\) takes first \(M_2\) columns of \(\mathcal{G}^i\). The equation of embedding network \(\mathcal{N}\) can be found at
deepmd.utils.network.embedding_net().- Parameters
- rcut
The cut-off radius \(r_c\)
- rcut_smth
From where the environment matrix should be smoothed \(r_s\)
- sel
list[int] sel[i] specifies the maxmum number of type i atoms in the cut-off radius
- neuron
list[int] Number of neurons in each hidden layers of the embedding net \(\mathcal{N}\)
- axis_neuron
Number of the axis neuron \(M_2\) (number of columns of the sub-matrix of the embedding matrix)
- resnet_dt
Time-step dt in the resnet construction: y = x + dt * phi (Wx + b)
- trainable
If the weights of embedding net are trainable.
- type_one_side
Try to build N_types embedding nets. Otherwise, building N_types^2 embedding nets
- exclude_types
List[List[int]] The excluded pairs of types which have no interaction with each other. For example, [[0, 1]] means no interaction between type 0 and type 1.
- set_davg_zero
Set the shift of embedding net input to zero.
- activation_function
The activation function in the embedding net. Supported options are “relu”, “relu6”, “softplus”, “sigmoid”, “tanh”, “gelu”, “gelu_tf”, “None”, “none”.
- precision
The precision of the embedding net parameters. Supported options are “default”, “float16”, “float32”, “float64”, “bfloat16”.
- multi_task
If the model has multi fitting nets to train.
- spin
The deepspin object.
References
- 1(1,2)
Linfeng Zhang, Jiequn Han, Han Wang, Wissam A. Saidi, Roberto Car, and E. Weinan. 2018. End-to-end symmetry preserving inter-atomic potential energy model for finite and extended systems. In Proceedings of the 32nd International Conference on Neural Information Processing Systems (NIPS’18). Curran Associates Inc., Red Hook, NY, USA, 4441-4451.
Methods
__call__(*args, **kwargs)Forward pass in NumPy implementation.
call(coord_ext, atype_ext, nlist)Compute the descriptor.
cal_g
deserialize
serialize
- call(coord_ext, atype_ext, nlist)[source]
Compute the descriptor.
- Parameters
- coord_ext
The extended coordinates of atoms. shape: nf x (nallx3)
- atype_ext
The extended aotm types. shape: nf x nall
- nlist
The neighbor list. shape: nf x nloc x nnei
- Returns
descriptorThe descriptor. shape: nf x nloc x ng x axis_neuron
- classmethod deserialize(data: dict) DescrptSeA[source]
deepmd_utils.utils package
Submodules
deepmd_utils.utils.argcheck module
- class deepmd_utils.utils.argcheck.ArgsPlugin[source]
Bases:
objectMethods
get_all_argument([exclude_hybrid])Get all arguments.
register(name[, alias])Register a descriptor argument plugin.
- deepmd_utils.utils.argcheck.descrpt_variant_type_args(exclude_hybrid: bool = False) Variant[source]
- deepmd_utils.utils.argcheck.normalize_fitting_weight(fitting_keys, data_keys, fitting_weight=None)[source]
deepmd_utils.utils.argcheck_nvnmd module
deepmd_utils.utils.batch_size module
- class deepmd_utils.utils.batch_size.AutoBatchSize(initial_batch_size: int = 1024, factor: float = 2.0)[source]
Bases:
ABCThis class allows DeePMD-kit to automatically decide the maximum batch size that will not cause an OOM error.
- Parameters
Notes
In some CPU environments, the program may be directly killed when OOM. In this case, by default the batch size will not be increased for CPUs. The environment variable DP_INFER_BATCH_SIZE can be set as the batch size.
In other cases, we assume all OOM error will raise
OutOfMemoryError.- Attributes
Methods
execute(callable, start_index, natoms)Excuate a method with given batch size.
execute_all(callable, total_size, natoms, ...)Excuate a method with all given data.
Check if GPU is available.
is_oom_error(e)Check if the exception is an OOM error.
- execute(callable: Callable, start_index: int, natoms: int) Tuple[int, tuple][source]
Excuate a method with given batch size.
- Parameters
- Returns
- Raises
OutOfMemoryErrorOOM when batch size is 1
- execute_all(callable: Callable, total_size: int, natoms: int, *args, **kwargs) Tuple[ndarray][source]
Excuate a method with all given data.
deepmd_utils.utils.compat module
Module providing compatibility between 0.x.x and 1.x.x input versions.
- deepmd_utils.utils.compat.convert_input_v0_v1(jdata: Dict[str, Any], warning: bool = True, dump: Optional[Union[str, Path]] = None) Dict[str, Any][source]
Convert input from v0 format to v1.
- deepmd_utils.utils.compat.convert_input_v1_v2(jdata: Dict[str, Any], warning: bool = True, dump: Optional[Union[str, Path]] = None) Dict[str, Any][source]
- deepmd_utils.utils.compat.deprecate_numb_test(jdata: Dict[str, Any], warning: bool = True, dump: Optional[Union[str, Path]] = None) Dict[str, Any][source]
Deprecate numb_test since v2.1. It has taken no effect since v2.0.
See #1243.
deepmd_utils.utils.data module
- class deepmd_utils.utils.data.DeepmdData(sys_path: str, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set: bool = False, sort_atoms: bool = True)[source]
Bases:
objectClass for a data system.
It loads data from hard disk, and mantains the data as a data_dict
- Parameters
- sys_path
Path to the data system
- set_prefix
Prefix for the directories of different sets
- shuffle_test
If the test data are shuffled
- type_map
Gives the name of different atom types
- optional_type_map
If the type_map.raw in each system is optional
- modifier
Data modifier that has the method modify_data
- trn_all_set
Use all sets as training dataset. Otherwise, if the number of sets is more than 1, the last set is left for test.
- sort_atomsbool
Sort atoms by atom types. Required to enable when the data is directly feeded to descriptors except mixed types.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
avg(key)Return the average value of an item.
check_batch_size(batch_size)Check if the system can get a batch of data with batch_size frames.
check_test_size(test_size)Check if the system can get a test dataset with test_size frames.
Get atom types.
get_batch(batch_size)Get a batch of data with batch_size frames.
Get the data_dict.
Get number of atoms.
get_natoms_vec(ntypes)Get number of atoms and number of atoms in different types.
Number of atom types in the system.
get_numb_batch(batch_size, set_idx)Get the number of batches in a set.
Get number of training sets.
get_sys_numb_batch(batch_size)Get the number of batches in the data system.
get_test([ntests])Get the test data with ntests frames.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
reset_get_batch
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0, dtype: Optional[dtype] = None)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default
float, default=0. default value of data
- dtype
np.dtype,optional the dtype of data, overwrites high_prec if provided
- check_batch_size(batch_size)[source]
Check if the system can get a batch of data with batch_size frames.
- check_test_size(test_size)[source]
Check if the system can get a test dataset with test_size frames.
- get_batch(batch_size: int) dict[source]
Get a batch of data with batch_size frames. The frames are randomly picked from the data system.
- Parameters
- batch_size
size of the batch
- get_natoms_vec(ntypes: int)[source]
Get number of atoms and number of atoms in different types.
- Parameters
- ntypes
Number of types (may be larger than the actual number of types in the system).
- Returns
natomsnatoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms
- get_test(ntests: int = -1) dict[source]
Get the test data with ntests frames.
- Parameters
- ntests
Size of the test data set. If ntests is -1, all test data will be get.
deepmd_utils.utils.data_system module
- class deepmd_utils.utils.data_system.DeepmdDataSystem(systems: List[str], batch_size: int, test_size: int, rcut: Optional[float] = None, set_prefix: str = 'set', shuffle_test: bool = True, type_map: Optional[List[str]] = None, optional_type_map: bool = True, modifier=None, trn_all_set=False, sys_probs=None, auto_prob_style='prob_sys_size', sort_atoms: bool = True)[source]
Bases:
objectClass for manipulating many data systems.
It is implemented with the help of DeepmdData
- Attributes
default_meshMesh for each system.
Methods
add(key, ndof[, atomic, must, high_prec, ...])Add a data item that to be loaded.
add_dict(adict)Add items to the data system by a dict.
get_batch([sys_idx])Get a batch of data from the data systems.
Get a batch of data from the data systems in the mixed way.
Get the batch size.
get_batch_standard([sys_idx])Get a batch of data from the data systems in the standard way.
Get the total number of batches.
Get the number of data systems.
Get the number of types.
get_sys(idx)Get a certain data system.
get_sys_ntest([sys_idx])Get number of tests for the currently selected system, or one defined by sys_idx.
get_test([sys_idx, n_test])Get test data from the the data systems.
Get the type map.
reduce(key_out, key_in)Generate a new item from the reduction of another atom.
compute_energy_shift
get_data_dict
print_summary
set_sys_probs
- add(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[List[int]] = None, repeat: int = 1, default: float = 0.0)[source]
Add a data item that to be loaded.
- Parameters
- key
The key of the item. The corresponding data is stored in sys_path/set.*/key.npy
- ndof
The number of dof
- atomic
The item is an atomic property. If False, the size of the data should be nframes x ndof If True, the size of data should be nframes x natoms x ndof
- must
The data file sys_path/set.*/key.npy must exist. If must is False and the data file does not exist, the data_dict[find_key] is set to 0.0
- high_prec
Load the data and store in float64, otherwise in float32
- type_sel
Select certain type of atoms
- repeat
The data will be repeated repeat times.
- default, default=0.
Default value of data
- add_dict(adict: dict) None[source]
Add items to the data system by a dict. adict should have items like .. code-block:: python.
- adict[key] = {
“ndof”: ndof, “atomic”: atomic, “must”: must, “high_prec”: high_prec, “type_sel”: type_sel, “repeat”: repeat,
}
For the explaination of the keys see add
- get_batch(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems.
- Parameters
- sys_idx
int The index of system from which the batch is get. If sys_idx is not None, sys_probs and auto_prob_style are ignored If sys_idx is None, automatically determine the system according to sys_probs or auto_prob_style, see the following. This option does not work for mixed systems.
- sys_idx
- Returns
dictThe batch data
- get_batch_mixed() dict[source]
Get a batch of data from the data systems in the mixed way.
- Returns
dictThe batch data
- get_batch_standard(sys_idx: Optional[int] = None) dict[source]
Get a batch of data from the data systems in the standard way.
- get_sys(idx: int) DeepmdData[source]
Get a certain data system.
- get_sys_ntest(sys_idx=None)[source]
Get number of tests for the currently selected system, or one defined by sys_idx.
- get_test(sys_idx: Optional[int] = None, n_test: int = -1)[source]
Get test data from the the data systems.
- Parameters
- sys_idx
The test dat of system with index sys_idx will be returned. If is None, the currently selected system will be returned.
- n_test
Number of test data. If set to -1 all test data will be get.
deepmd_utils.utils.errors module
deepmd_utils.utils.model_stat module
- deepmd_utils.utils.model_stat.make_stat_input(data, nbatches, merge_sys=True)[source]
Pack data for statistics.
- Parameters
- Returns
- all_stat:
A dictionary of list of list storing data for stat. if merge_sys == False data can be accessed by
all_stat[key][sys_idx][batch_idx][frame_idx]
- else merge_sys == True can be accessed by
all_stat[key][batch_idx][frame_idx]
deepmd_utils.utils.pair_tab module
- class deepmd_utils.utils.pair_tab.PairTab(filename: str)[source]
Bases:
objectPairwise tabulated potential.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
Methods
get()Get the serialized table.
reinit(filename)Initialize the tabulated interaction.
- reinit(filename: str) None[source]
Initialize the tabulated interaction.
- Parameters
- filename
File name for the short-range tabulated potential. The table is a text data file with (N_t + 1) * N_t / 2 + 1 columes. The first colume is the distance between atoms. The second to the last columes are energies for pairs of certain types. For example we have two atom types, 0 and 1. The columes from 2nd to 4th are for 0-0, 0-1 and 1-1 correspondingly.
deepmd_utils.utils.path module
- class deepmd_utils.utils.path.DPH5Path(path: str)[source]
Bases:
DPPathThe path class to data system (DeepmdData) for HDF5 files.
- Parameters
- path
str path
- path
Notes
- OS - HDF5 relationship:
directory - Group file - Dataset
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt([dtype])Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- class deepmd_utils.utils.path.DPOSPath(path: str)[source]
Bases:
DPPathThe OS path class to data system (DeepmdData) for real directories.
- Parameters
- path
str path
- path
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt(**kwargs)Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- load_txt(**kwargs) ndarray[source]
Load NumPy array from text.
- Returns
np.ndarrayloaded NumPy array
- class deepmd_utils.utils.path.DPPath(path: str)[source]
Bases:
ABCThe path class to data system (DeepmdData).
- Parameters
- path
str path
- path
Methods
glob(pattern)Search path using the glob pattern.
is_dir()Check if self is directory.
is_file()Check if self is file.
Load NumPy array.
load_txt(**kwargs)Load NumPy array from text.
rglob(pattern)This is like calling
DPPath.glob()with **/ added in front of the given relative pattern.- abstract load_numpy() ndarray[source]
Load NumPy array.
- Returns
np.ndarrayloaded NumPy array
- abstract load_txt(**kwargs) ndarray[source]
Load NumPy array from text.
- Returns
np.ndarrayloaded NumPy array
deepmd_utils.utils.plugin module
Base of plugin systems.
- class deepmd_utils.utils.plugin.Plugin[source]
Bases:
objectA class to register and restore plugins.
Examples
>>> plugin = Plugin() >>> @plugin.register("xx") def xxx(): pass >>> print(plugin.plugins['xx'])
Methods
get_plugin(key)Visit a plugin by key.
register(key)Register a plugin.
- class deepmd_utils.utils.plugin.PluginVariant(*args, **kwargs)[source]
Bases:
objectA class to remove type from input arguments.
- class deepmd_utils.utils.plugin.VariantABCMeta(name, bases, namespace, **kwargs)[source]
Bases:
VariantMeta,ABCMetaMethods
__call__(*args, **kwargs)Remove type and keys that starts with underline.
mro(/)Return a type's method resolution order.
register(subclass)Register a virtual subclass of an ABC.
deepmd_utils.utils.random module
- deepmd_utils.utils.random.choice(a: ndarray, p: Optional[ndarray] = None)[source]
Generates a random sample from a given 1-D array.
- Parameters
- a
np.ndarray A random sample is generated from its elements.
- p
np.ndarray The probabilities associated with each entry in a.
- a
- Returns
np.ndarrayarrays with results and their shapes
- deepmd_utils.utils.random.random(size=None)[source]
Return random floats in the half-open interval [0.0, 1.0).
- Parameters
- size
Output shape.
- Returns
np.ndarrayArrays with results and their shapes.
- deepmd_utils.utils.random.seed(val: Optional[int] = None)[source]
Seed the generator.
- Parameters
- val
int Seed.
- val
- deepmd_utils.utils.random.shuffle(x: ndarray)[source]
Modify a sequence in-place by shuffling its contents.
- Parameters
- x
np.ndarray The array or list to be shuffled.
- x
deepmd_utils.utils.weight_avg module
Submodules
deepmd_utils.common module
- deepmd_utils.common.add_data_requirement(key: str, ndof: int, atomic: bool = False, must: bool = False, high_prec: bool = False, type_sel: Optional[bool] = None, repeat: int = 1, default: float = 0.0, dtype: Optional[dtype] = None)[source]
Specify data requirements for training.
- Parameters
- key
str type of data stored in corresponding *.npy file e.g. forces or energy
- ndof
int number of the degrees of freedom, this is tied to atomic parameter e.g. forces have atomic=True and ndof=3
- atomicbool,
optional specifies whwther the ndof keyworrd applies to per atom quantity or not, by default False
- mustbool,
optional specifi if the *.npy data file must exist, by default False
- high_precbool,
optional if true load data to np.float64 else np.float32, by default False
- type_selbool,
optional select only certain type of atoms, by default None
- repeat
int,optional if specify repaeat data repeat times, by default 1
- default
float,optional, default=0. default value of data
- dtype
np.dtype,optional the dtype of data, overwrites high_prec if provided
- key
- deepmd_utils.common.expand_sys_str(root_dir: Union[str, Path]) List[str][source]
Recursively iterate over directories taking those that contain type.raw file.
- deepmd_utils.common.get_np_precision(precision: _PRECISION) dtype[source]
Get numpy precision constant from string.
- Parameters
- precision
_PRECISION string name of numpy constant or default
- precision
- Returns
np.dtypenumpy presicion constant
- Raises
RuntimeErrorif string is invalid
- deepmd_utils.common.j_loader(filename: Union[str, Path]) Dict[str, Any][source]
Load yaml or json settings file.
- deepmd_utils.common.j_must_have(jdata: Dict[str, _DICT_VAL], key: str, deprecated_key: List[str] = []) _DICT_VAL[source]
Assert that supplied dictionary conaines specified key.
- Returns
_DICT_VALvalue that was store unde supplied key
- Raises
RuntimeErrorif the key is not present
- deepmd_utils.common.make_default_mesh(pbc: bool, mixed_type: bool) ndarray[source]
Make mesh.
Only the size of mesh matters, not the values: * 6 for PBC, no mixed types * 0 for no PBC, no mixed types * 7 for PBC, mixed types * 1 for no PBC, mixed types
- Parameters
- Returns
np.ndarraymesh
- deepmd_utils.common.select_idx_map(atom_types: ndarray, select_types: ndarray) ndarray[source]
Build map of indices for element supplied element types from all atoms list.
- Parameters
- atom_types
np.ndarray array specifing type for each atoms as integer
- select_types
np.ndarray types of atoms you want to find indices for
- atom_types
- Returns
np.ndarrayindices of types of atoms defined by select_types in atom_types array
Warning
select_types array will be sorted before finding indices in atom_types
deepmd_utils.env module
- deepmd_utils.env.GLOBAL_ENER_FLOAT_PRECISION
alias of
float64
- deepmd_utils.env.GLOBAL_NP_FLOAT_PRECISION
alias of
float64
deepmd_utils.main module
The entry points for DeePMD-kit.
If only printing the help message, this module does not call the main DeePMD-kit module to avoid the slow import of TensorFlow.
- class deepmd_utils.main.RawTextArgumentDefaultsHelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]
Bases:
RawTextHelpFormatter,ArgumentDefaultsHelpFormatterThis formatter is used to print multile-line help message with default value.
Methods
format_help()start_section(heading)add_argument
add_arguments
add_text
add_usage
end_section
- deepmd_utils.main.main()[source]
DeePMD-kit new entry point.
- Raises
RuntimeErrorif no command was input
- deepmd_utils.main.main_parser() ArgumentParser[source]
DeePMD-Kit commandline options argument parser.
- Returns
argparse.ArgumentParsermain parser of DeePMD-kit
OP API
op_module
Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
- deepmd.env.op_module.AddFltNvnmd(x, w, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- class deepmd.env.op_module.Annotated(*args, **kwargs)
Bases:
objectAdd context specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int.
The first argument to Annotated must be a valid type.
Details:
It’s an error to call Annotated with less than two arguments.
Nested Annotated are flattened:
Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
Instantiating an annotated type is equivalent to instantiating the
underlying type:
Annotated[C, Ann1](5) == C(5)
Annotated can be used as a generic type alias:
Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
- deepmd.env.op_module.ConvertForwardMap(sub_forward_map, sub_natoms, natoms, name=None)
TODO: add doc.
- Parameters
sub_forward_map – A Tensor of type int32.
sub_natoms – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (forward_map, backward_map, new_natoms, mesh).
forward_map: A Tensor of type int32. backward_map: A Tensor of type int32. new_natoms: A Tensor of type int32. mesh: A Tensor of type int32.
- deepmd.env.op_module.CopyFltNvnmd(x, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (y1, y2).
y1: A Tensor. Has the same type as x. y2: A Tensor. Has the same type as x.
- deepmd.env.op_module.Descrpt(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, sel_a, sel_r, axis_rule, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
sel_a – A list of ints.
sel_r – A list of ints.
axis_rule – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, axis, rot_mat).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. axis: A Tensor of type int32. rot_mat: A Tensor. Has the same type as coord.
- deepmd.env.op_module.DescrptNorot(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeA(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeAEf(coord, type, natoms, box, mesh, ef, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeAEfPara(coord, type, natoms, box, mesh, ef, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeAEfVert(coord, type, natoms, box, mesh, ef, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeAMask(coord, type, mask, box, natoms, mesh, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
mask – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
natoms – A Tensor of type int32.
mesh – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DescrptSeR(coord, type, natoms, box, mesh, davg, dstd, rcut, rcut_smth, sel, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut – A float.
rcut_smth – A float.
sel – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.DotmulFltNvnmd(x, w, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.DprcPairwiseIdx(idxs, natoms, name=None)
TODO: add doc.
- Parameters
idxs – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (forward_qm_map, backward_qm_map, forward_qmmm_map, backward_qmmm_map, natoms_qm, natoms_qmmm, qmmm_frame_idx).
forward_qm_map: A Tensor of type int32. backward_qm_map: A Tensor of type int32. forward_qmmm_map: A Tensor of type int32. backward_qmmm_map: A Tensor of type int32. natoms_qm: A Tensor of type int32. natoms_qmmm: A Tensor of type int32. qmmm_frame_idx: A Tensor of type int32.
- deepmd.env.op_module.EwaldRecp(coord, charge, natoms, box, ewald_beta, ewald_h, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
charge – A Tensor. Must have the same type as coord.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
ewald_beta – A float.
ewald_h – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (energy, force, virial).
energy: A Tensor. Has the same type as coord. force: A Tensor. Has the same type as coord. virial: A Tensor. Has the same type as coord.
- deepmd.env.op_module.FltNvnmd(x, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.Gelu(x, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.GeluCustom(x, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.GeluGrad(dy, x, name=None)
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.GeluGradCustom(dy, x, name=None)
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.GeluGradGrad(dy, dy_, x, name=None)
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as dy.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.GeluGradGradCustom(dy, dy_, x, name=None)
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as dy.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.MapAparam(aparam, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
aparam – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as aparam.
- deepmd.env.op_module.MapFltNvnmd(x, table, table_grad, table_info, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
table – A Tensor. Must have the same type as x.
table_grad – A Tensor. Must have the same type as x.
table_info – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.MatmulFitnetNvnmd(x, w, nbitx, nbitw, normw, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
nbitx – An int.
nbitw – An int.
normw – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.MatmulFlt2fixNvnmd(x, w, nbit, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
nbit – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.MatmulFltNvnmd(x, w, normx, normw, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
normx – An int.
normw – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.MulFltNvnmd(x, w, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.NeighborStat(coord, type, natoms, box, mesh, rcut, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
rcut – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (max_nbor_size, min_nbor_dist).
max_nbor_size: A Tensor of type int32. min_nbor_dist: A Tensor. Has the same type as coord.
- deepmd.env.op_module.PairTab(table_info, table_data, type, rij, nlist, natoms, scale, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
table_info – A Tensor of type float64.
table_data – A Tensor of type float64.
type – A Tensor of type int32.
rij – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
scale – A Tensor. Must have the same type as rij.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (atom_energy, force, atom_virial).
atom_energy: A Tensor. Has the same type as rij. force: A Tensor. Has the same type as rij. atom_virial: A Tensor. Has the same type as rij.
- deepmd.env.op_module.ParallelProdForceSeA(net_deriv, in_deriv, nlist, natoms, n_a_sel, n_r_sel, parallel=False, start_frac=0, end_frac=1, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
parallel – An optional bool. Defaults to False.
start_frac – An optional float. Defaults to 0.
end_frac – An optional float. Defaults to 1.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdEnvMatA(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
Compute the environment matrix for descriptor se_e2_a.
Each row of the environment matrix \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]In the above equation, \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Note that the environment matrix is normalized by davg and dstd.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64. The coordinates of atoms.
type – A Tensor of type int32. The types of atoms.
natoms – A Tensor of type int32. The number of atoms. This tensor has the length of Ntypes + 2. natoms[0]: number of local atoms. natoms[1]: total number of atoms held by this processor. natoms[i]: 2 <= i < Ntypes+2, number of type i atoms.
box – A Tensor. Must have the same type as coord. The box of frames.
mesh – A Tensor of type int32. Gor historical reasons, only the length of the Tensor matters. If size of mesh == 6, pbc is assumed. If size of mesh == 0, no-pbc is assumed.
davg – A Tensor. Must have the same type as coord. Average value of the environment matrix for normalization.
dstd – A Tensor. Must have the same type as coord. Standard deviation of the environment matrix for normalization.
rcut_a – A float. This argument is not used.
rcut_r – A float. The cutoff radius for the environment matrix.
rcut_r_smth – A float. From where the environment matrix should be smoothed.
sel_a – A list of ints. sel_a[i] specifies the maxmum number of type i atoms in the cut-off radius.
sel_r – A list of ints. This argument is not used.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. The environment matrix. descrpt_deriv: A Tensor. Has the same type as coord. The derivative of the environment matrix. rij: A Tensor. Has the same type as coord. The distance between the atoms. nlist: A Tensor of type int32. The neighbor list of each atom.
- deepmd.env.op_module.ProdEnvMatAMix(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
Compute the environment matrix mixing the atom types.
The sorting of neighbor atoms depends not on atom types, but on the distance and index. The atoms in nlist matrix will gather forward and thus save space for gaps of types in ProdEnvMatA, resulting in optimized and relative small sel_a.
The additional outputs are listed as following:
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, ntype, nmask).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. ntype: A Tensor of type int32. The corresponding atom types in nlist. nmask: A Tensor of type bool. The atom mask in nlist.
- deepmd.env.op_module.ProdEnvMatAMixNvnmdQuantize(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, ntype, nmask).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. ntype: A Tensor of type int32. nmask: A Tensor of type bool.
- deepmd.env.op_module.ProdEnvMatANvnmdQuantize(coord, type, natoms, box, mesh, davg, dstd, rcut_a, rcut_r, rcut_r_smth, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.ProdEnvMatR(coord, type, natoms, box, mesh, davg, dstd, rcut, rcut_smth, sel, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut – A float.
rcut_smth – A float.
sel – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.ProdForce(net_deriv, in_deriv, nlist, axis, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdForceNorot(net_deriv, in_deriv, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdForceSeA(net_deriv, in_deriv, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdForceSeAMask(net_deriv, in_deriv, mask, nlist, total_atom_num, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
mask – A Tensor of type int32.
nlist – A Tensor of type int32.
total_atom_num – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdForceSeR(net_deriv, in_deriv, nlist, natoms, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdVirial(net_deriv, in_deriv, rij, nlist, axis, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdVirialNorot(net_deriv, in_deriv, rij, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdVirialSeA(net_deriv, in_deriv, rij, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.ProdVirialSeR(net_deriv, in_deriv, rij, nlist, natoms, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.QuantizeNvnmd(x, isround, nbit1, nbit2, nbit3, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
isround – An int.
nbit1 – An int.
nbit2 – An int.
nbit3 – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.SoftMinForce(du, sw_deriv, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
du – A Tensor. Must be one of the following types: float32, float64.
sw_deriv – A Tensor. Must have the same type as du.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as du.
- deepmd.env.op_module.SoftMinSwitch(type, rij, nlist, natoms, sel_a, sel_r, alpha, rmin, rmax, name=None)
TODO: add doc.
- Parameters
type – A Tensor of type int32.
rij – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
sel_a – A list of ints.
sel_r – A list of ints.
alpha – A float.
rmin – A float.
rmax – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (sw_value, sw_deriv).
sw_value: A Tensor. Has the same type as rij. sw_deriv: A Tensor. Has the same type as rij.
- deepmd.env.op_module.SoftMinVirial(du, sw_deriv, rij, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
du – A Tensor. Must be one of the following types: float32, float64.
sw_deriv – A Tensor. Must have the same type as du.
rij – A Tensor. Must have the same type as du.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as du. atom_virial: A Tensor. Has the same type as du.
- deepmd.env.op_module.TabulateFusion(table, table_info, em_x, em, last_layer_size, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionGrad(table, table_info, em_x, em, dy, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionGradGrad(table, table_info, em_x, em, dz_dy_dem_x, dz_dy_dem, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeA(table, table_info, em_x, em, last_layer_size, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeAGrad(table, table_info, em_x, em, dy, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeAGradGrad(table, table_info, em_x, em, dz_dy_dem_x, dz_dy_dem, descriptor, is_sorted=True, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeAtten(table, table_info, em_x, em, two_embed, last_layer_size, is_sorted=True, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
last_layer_size – An int.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeAttenGrad(table, table_info, em_x, em, two_embed, dy, descriptor, is_sorted=True, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem, dy_dtwo).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table. dy_dtwo: A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeAttenGradGrad(table, table_info, em_x, em, two_embed, dz_dy_dem_x, dz_dy_dem, dz_dy_dtwo, descriptor, is_sorted=True, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
dz_dy_dtwo – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeR(table, table_info, em, last_layer_size, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeRGrad(table, table_info, em, dy, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeRGradGrad(table, table_info, em, dz_dy_dem, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeT(table, table_info, em_x, em, last_layer_size, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeTGrad(table, table_info, em_x, em, dy, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.TabulateFusionSeTGradGrad(table, table_info, em_x, em, dz_dy_dem_x, dz_dy_dem, descriptor, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.Tanh4FltNvnmd(x, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.UnaggregatedDy2Dx(z, w, dy_dx, dy2_dx, ybar, functype, name=None)
TODO: add doc.
- Parameters
z – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as z.
dy_dx – A Tensor. Must have the same type as z.
dy2_dx – A Tensor. Must have the same type as z.
ybar – A Tensor. Must have the same type as z.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as z.
- deepmd.env.op_module.UnaggregatedDy2DxS(y, dy, w, xbar, functype, name=None)
TODO: add doc.
- Parameters
y – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as y.
w – A Tensor. Must have the same type as y.
xbar – A Tensor. Must have the same type as y.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as y.
- deepmd.env.op_module.UnaggregatedDyDx(z, w, dy_dx, ybar, functype, name=None)
TODO: add doc.
- Parameters
z – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as z.
dy_dx – A Tensor. Must have the same type as z.
ybar – A Tensor. Must have the same type as z.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as z.
- deepmd.env.op_module.UnaggregatedDyDxS(y, w, xbar, functype, name=None)
TODO: add doc.
- Parameters
y – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as y.
xbar – A Tensor. Must have the same type as y.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as y.
- deepmd.env.op_module.add_flt_nvnmd(x: Any, w: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.convert_forward_map(sub_forward_map: Any, sub_natoms: Any, natoms: Any, name=None)
TODO: add doc.
- Parameters
sub_forward_map – A Tensor of type int32.
sub_natoms – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (forward_map, backward_map, new_natoms, mesh).
forward_map: A Tensor of type int32. backward_map: A Tensor of type int32. new_natoms: A Tensor of type int32. mesh: A Tensor of type int32.
- deepmd.env.op_module.copy_flt_nvnmd(x: Any, name=None)
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (y1, y2).
y1: A Tensor. Has the same type as x. y2: A Tensor. Has the same type as x.
- deepmd.env.op_module.descrpt(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, sel_a, sel_r, axis_rule, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
sel_a – A list of ints.
sel_r – A list of ints.
axis_rule – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, axis, rot_mat).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. axis: A Tensor of type int32. rot_mat: A Tensor. Has the same type as coord.
- deepmd.env.op_module.descrpt_norot(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_a(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_a_ef(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, ef: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_a_ef_para(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, ef: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_a_ef_vert(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, ef: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
ef – A Tensor. Must have the same type as coord.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_a_mask(coord: Any, type: Any, mask: Any, box: Any, natoms: Any, mesh: Any, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
mask – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
natoms – A Tensor of type int32.
mesh – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.descrpt_se_r(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut: float, rcut_smth: float, sel, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut – A float.
rcut_smth – A float.
sel – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.dotmul_flt_nvnmd(x: Any, w: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.dprc_pairwise_idx(idxs: Any, natoms: Any, name=None)
TODO: add doc.
- Parameters
idxs – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (forward_qm_map, backward_qm_map, forward_qmmm_map, backward_qmmm_map, natoms_qm, natoms_qmmm, qmmm_frame_idx).
forward_qm_map: A Tensor of type int32. backward_qm_map: A Tensor of type int32. forward_qmmm_map: A Tensor of type int32. backward_qmmm_map: A Tensor of type int32. natoms_qm: A Tensor of type int32. natoms_qmmm: A Tensor of type int32. qmmm_frame_idx: A Tensor of type int32.
- deepmd.env.op_module.ewald_recp(coord: Any, charge: Any, natoms: Any, box: Any, ewald_beta: float, ewald_h: float, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
charge – A Tensor. Must have the same type as coord.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
ewald_beta – A float.
ewald_h – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (energy, force, virial).
energy: A Tensor. Has the same type as coord. force: A Tensor. Has the same type as coord. virial: A Tensor. Has the same type as coord.
- deepmd.env.op_module.flt_nvnmd(x: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.gelu(x: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.gelu_custom(x: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.gelu_grad(dy: Any, x: Any, name=None) Any
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.gelu_grad_custom(dy: Any, x: Any, name=None) Any
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.gelu_grad_grad(dy: Any, dy_: Any, x: Any, name=None) Any
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as dy.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.gelu_grad_grad_custom(dy: Any, dy_: Any, x: Any, name=None) Any
TODO: add doc.
- Parameters
dy – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as dy.
x – A Tensor. Must have the same type as dy.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as dy.
- deepmd.env.op_module.map_aparam(aparam: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
aparam – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as aparam.
- deepmd.env.op_module.map_flt_nvnmd(x: Any, table: Any, table_grad: Any, table_info: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
table – A Tensor. Must have the same type as x.
table_grad – A Tensor. Must have the same type as x.
table_info – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.matmul_fitnet_nvnmd(x: Any, w: Any, nbitx: int, nbitw: int, normw: int, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
nbitx – An int.
nbitw – An int.
normw – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.matmul_flt2fix_nvnmd(x: Any, w: Any, nbit: int, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
nbit – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.matmul_flt_nvnmd(x: Any, w: Any, normx: int, normw: int, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
normx – An int.
normw – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.mul_flt_nvnmd(x: Any, w: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as x.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.neighbor_stat(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, rcut: float, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
rcut – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (max_nbor_size, min_nbor_dist).
max_nbor_size: A Tensor of type int32. min_nbor_dist: A Tensor. Has the same type as coord.
- deepmd.env.op_module.pair_tab(table_info: Any, table_data: Any, type: Any, rij: Any, nlist: Any, natoms: Any, scale: Any, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
table_info – A Tensor of type float64.
table_data – A Tensor of type float64.
type – A Tensor of type int32.
rij – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
scale – A Tensor. Must have the same type as rij.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (atom_energy, force, atom_virial).
atom_energy: A Tensor. Has the same type as rij. force: A Tensor. Has the same type as rij. atom_virial: A Tensor. Has the same type as rij.
- deepmd.env.op_module.parallel_prod_force_se_a(net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, parallel: bool = False, start_frac: float = 0, end_frac: float = 1, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
parallel – An optional bool. Defaults to False.
start_frac – An optional float. Defaults to 0.
end_frac – An optional float. Defaults to 1.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_env_mat_a(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
Compute the environment matrix for descriptor se_e2_a.
Each row of the environment matrix \(\mathcal{R}^i\) can be constructed as follows
\[(\mathcal{R}^i)_j = [ \begin{array}{c} s(r_{ji}) & \frac{s(r_{ji})x_{ji}}{r_{ji}} & \frac{s(r_{ji})y_{ji}}{r_{ji}} & \frac{s(r_{ji})z_{ji}}{r_{ji}} \end{array} ]\]In the above equation, \(\mathbf{R}_{ji}=\mathbf{R}_j-\mathbf{R}_i = (x_{ji}, y_{ji}, z_{ji})\) is the relative coordinate and \(r_{ji}=\lVert \mathbf{R}_{ji} \lVert\) is its norm. The switching function \(s(r)\) is defined as:
\[\begin{split}s(r)= \begin{cases} \frac{1}{r}, & r<r_s \\ \frac{1}{r} \{ {(\frac{r - r_s}{ r_c - r_s})}^3 (-6 {(\frac{r - r_s}{ r_c - r_s})}^2 +15 \frac{r - r_s}{ r_c - r_s} -10) +1 \}, & r_s \leq r<r_c \\ 0, & r \geq r_c \end{cases}\end{split}\]Note that the environment matrix is normalized by davg and dstd.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64. The coordinates of atoms.
type – A Tensor of type int32. The types of atoms.
natoms – A Tensor of type int32. The number of atoms. This tensor has the length of Ntypes + 2. natoms[0]: number of local atoms. natoms[1]: total number of atoms held by this processor. natoms[i]: 2 <= i < Ntypes+2, number of type i atoms.
box – A Tensor. Must have the same type as coord. The box of frames.
mesh – A Tensor of type int32. Gor historical reasons, only the length of the Tensor matters. If size of mesh == 6, pbc is assumed. If size of mesh == 0, no-pbc is assumed.
davg – A Tensor. Must have the same type as coord. Average value of the environment matrix for normalization.
dstd – A Tensor. Must have the same type as coord. Standard deviation of the environment matrix for normalization.
rcut_a – A float. This argument is not used.
rcut_r – A float. The cutoff radius for the environment matrix.
rcut_r_smth – A float. From where the environment matrix should be smoothed.
sel_a – A list of ints. sel_a[i] specifies the maxmum number of type i atoms in the cut-off radius.
sel_r – A list of ints. This argument is not used.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. The environment matrix. descrpt_deriv: A Tensor. Has the same type as coord. The derivative of the environment matrix. rij: A Tensor. Has the same type as coord. The distance between the atoms. nlist: A Tensor of type int32. The neighbor list of each atom.
- deepmd.env.op_module.prod_env_mat_a_mix(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
Compute the environment matrix mixing the atom types.
The sorting of neighbor atoms depends not on atom types, but on the distance and index. The atoms in nlist matrix will gather forward and thus save space for gaps of types in ProdEnvMatA, resulting in optimized and relative small sel_a.
The additional outputs are listed as following:
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, ntype, nmask).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. ntype: A Tensor of type int32. The corresponding atom types in nlist. nmask: A Tensor of type bool. The atom mask in nlist.
- deepmd.env.op_module.prod_env_mat_a_mix_nvnmd_quantize(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist, ntype, nmask).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32. ntype: A Tensor of type int32. nmask: A Tensor of type bool.
- deepmd.env.op_module.prod_env_mat_a_nvnmd_quantize(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut_a: float, rcut_r: float, rcut_r_smth: float, sel_a, sel_r, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut_a – A float.
rcut_r – A float.
rcut_r_smth – A float.
sel_a – A list of ints.
sel_r – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.prod_env_mat_r(coord: Any, type: Any, natoms: Any, box: Any, mesh: Any, davg: Any, dstd: Any, rcut: float, rcut_smth: float, sel, name=None)
TODO: add doc.
- Parameters
coord – A Tensor. Must be one of the following types: float32, float64.
type – A Tensor of type int32.
natoms – A Tensor of type int32.
box – A Tensor. Must have the same type as coord.
mesh – A Tensor of type int32.
davg – A Tensor. Must have the same type as coord.
dstd – A Tensor. Must have the same type as coord.
rcut – A float.
rcut_smth – A float.
sel – A list of ints.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (descrpt, descrpt_deriv, rij, nlist).
descrpt: A Tensor. Has the same type as coord. descrpt_deriv: A Tensor. Has the same type as coord. rij: A Tensor. Has the same type as coord. nlist: A Tensor of type int32.
- deepmd.env.op_module.prod_force(net_deriv: Any, in_deriv: Any, nlist: Any, axis: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_force_norot(net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_force_se_a(net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_force_se_a_mask(net_deriv: Any, in_deriv: Any, mask: Any, nlist: Any, total_atom_num: int, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
mask – A Tensor of type int32.
nlist – A Tensor of type int32.
total_atom_num – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_force_se_r(net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, name=None) Any
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_virial(net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, axis: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_virial_norot(net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_virial_se_a(net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.prod_virial_se_r(net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, natoms: Any, name=None)
TODO: add doc.
- Parameters
net_deriv – A Tensor. Must be one of the following types: float32, float64.
in_deriv – A Tensor. Must have the same type as net_deriv.
rij – A Tensor. Must have the same type as net_deriv.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as net_deriv. atom_virial: A Tensor. Has the same type as net_deriv.
- deepmd.env.op_module.quantize_nvnmd(x: Any, isround: int, nbit1: int, nbit2: int, nbit3: int, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
isround – An int.
nbit1 – An int.
nbit2 – An int.
nbit3 – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.soft_min_force(du: Any, sw_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
du – A Tensor. Must be one of the following types: float32, float64.
sw_deriv – A Tensor. Must have the same type as du.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as du.
- deepmd.env.op_module.soft_min_switch(type: Any, rij: Any, nlist: Any, natoms: Any, sel_a, sel_r, alpha: float, rmin: float, rmax: float, name=None)
TODO: add doc.
- Parameters
type – A Tensor of type int32.
rij – A Tensor. Must be one of the following types: float32, float64.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
sel_a – A list of ints.
sel_r – A list of ints.
alpha – A float.
rmin – A float.
rmax – A float.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (sw_value, sw_deriv).
sw_value: A Tensor. Has the same type as rij. sw_deriv: A Tensor. Has the same type as rij.
- deepmd.env.op_module.soft_min_virial(du: Any, sw_deriv: Any, rij: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None)
TODO: add doc.
- Parameters
du – A Tensor. Must be one of the following types: float32, float64.
sw_deriv – A Tensor. Must have the same type as du.
rij – A Tensor. Must have the same type as du.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (virial, atom_virial).
virial: A Tensor. Has the same type as du. atom_virial: A Tensor. Has the same type as du.
- deepmd.env.op_module.tabulate_fusion(table: Any, table_info: Any, em_x: Any, em: Any, last_layer_size: int, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_grad(table: Any, table_info: Any, em_x: Any, em: Any, dy: Any, descriptor: Any, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_grad_grad(table: Any, table_info: Any, em_x: Any, em: Any, dz_dy_dem_x: Any, dz_dy_dem: Any, descriptor: Any, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_a(table: Any, table_info: Any, em_x: Any, em: Any, last_layer_size: int, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_a_grad(table: Any, table_info: Any, em_x: Any, em: Any, dy: Any, descriptor: Any, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_a_grad_grad(table: Any, table_info: Any, em_x: Any, em: Any, dz_dy_dem_x: Any, dz_dy_dem: Any, descriptor: Any, is_sorted: bool = True, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_atten(table: Any, table_info: Any, em_x: Any, em: Any, two_embed: Any, last_layer_size: int, is_sorted: bool = True, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
last_layer_size – An int.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_atten_grad(table: Any, table_info: Any, em_x: Any, em: Any, two_embed: Any, dy: Any, descriptor: Any, is_sorted: bool = True, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem, dy_dtwo).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table. dy_dtwo: A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_atten_grad_grad(table: Any, table_info: Any, em_x: Any, em: Any, two_embed: Any, dz_dy_dem_x: Any, dz_dy_dem: Any, dz_dy_dtwo: Any, descriptor: Any, is_sorted: bool = True, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
two_embed – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
dz_dy_dtwo – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
is_sorted – An optional bool. Defaults to True.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_r(table: Any, table_info: Any, em: Any, last_layer_size: int, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_r_grad(table: Any, table_info: Any, em: Any, dy: Any, descriptor: Any, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_r_grad_grad(table: Any, table_info: Any, em: Any, dz_dy_dem: Any, descriptor: Any, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_t(table: Any, table_info: Any, em_x: Any, em: Any, last_layer_size: int, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
last_layer_size – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_t_grad(table: Any, table_info: Any, em_x: Any, em: Any, dy: Any, descriptor: Any, name=None)
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dy – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A tuple of Tensor objects (dy_dem_x, dy_dem).
dy_dem_x: A Tensor. Has the same type as table. dy_dem: A Tensor. Has the same type as table.
- deepmd.env.op_module.tabulate_fusion_se_t_grad_grad(table: Any, table_info: Any, em_x: Any, em: Any, dz_dy_dem_x: Any, dz_dy_dem: Any, descriptor: Any, name=None) Any
TODO: add doc.
- Parameters
table – A Tensor. Must be one of the following types: float32, float64.
table_info – A Tensor. Must have the same type as table.
em_x – A Tensor. Must have the same type as table.
em – A Tensor. Must have the same type as table.
dz_dy_dem_x – A Tensor. Must have the same type as table.
dz_dy_dem – A Tensor. Must have the same type as table.
descriptor – A Tensor. Must have the same type as table.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as table.
- deepmd.env.op_module.tanh4_flt_nvnmd(x: Any, name=None) Any
TODO: add doc.
- Parameters
x – A Tensor. Must be one of the following types: float32, float64.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as x.
- deepmd.env.op_module.unaggregated_dy2_dx(z: Any, w: Any, dy_dx: Any, dy2_dx: Any, ybar: Any, functype: Any, name=None) Any
TODO: add doc.
- Parameters
z – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as z.
dy_dx – A Tensor. Must have the same type as z.
dy2_dx – A Tensor. Must have the same type as z.
ybar – A Tensor. Must have the same type as z.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as z.
- deepmd.env.op_module.unaggregated_dy2_dx_s(y: Any, dy: Any, w: Any, xbar: Any, functype: Any, name=None) Any
TODO: add doc.
- Parameters
y – A Tensor. Must be one of the following types: float32, float64.
dy – A Tensor. Must have the same type as y.
w – A Tensor. Must have the same type as y.
xbar – A Tensor. Must have the same type as y.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as y.
- deepmd.env.op_module.unaggregated_dy_dx(z: Any, w: Any, dy_dx: Any, ybar: Any, functype: Any, name=None) Any
TODO: add doc.
- Parameters
z – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as z.
dy_dx – A Tensor. Must have the same type as z.
ybar – A Tensor. Must have the same type as z.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as z.
- deepmd.env.op_module.unaggregated_dy_dx_s(y: Any, w: Any, xbar: Any, functype: Any, name=None) Any
TODO: add doc.
- Parameters
y – A Tensor. Must be one of the following types: float32, float64.
w – A Tensor. Must have the same type as y.
xbar – A Tensor. Must have the same type as y.
functype – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as y.
op_grads_module
Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
- class deepmd.env.op_grads_module.Annotated(*args, **kwargs)
Bases:
objectAdd context specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int.
The first argument to Annotated must be a valid type.
Details:
It’s an error to call Annotated with less than two arguments.
Nested Annotated are flattened:
Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
Instantiating an annotated type is equivalent to instantiating the
underlying type:
Annotated[C, Ann1](5) == C(5)
Annotated can be used as a generic type alias:
Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
- deepmd.env.op_grads_module.ProdForceGrad(grad, net_deriv, in_deriv, nlist, axis, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdForceSeAGrad(grad, net_deriv, in_deriv, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdForceSeAMaskGrad(grad, net_deriv, in_deriv, mask, nlist, total_atom_num, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
mask – A Tensor of type int32.
nlist – A Tensor of type int32.
total_atom_num – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdForceSeRGrad(grad, net_deriv, in_deriv, nlist, natoms, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdVirialGrad(grad, net_deriv, in_deriv, rij, nlist, axis, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdVirialSeAGrad(grad, net_deriv, in_deriv, rij, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.ProdVirialSeRGrad(grad, net_deriv, in_deriv, rij, nlist, natoms, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.SoftMinForceGrad(grad, du, sw_deriv, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
du – A Tensor. Must have the same type as grad.
sw_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.SoftMinVirialGrad(grad, du, sw_deriv, rij, nlist, natoms, n_a_sel, n_r_sel, name=None)
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
du – A Tensor. Must have the same type as grad.
sw_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_force_grad(grad: Any, net_deriv: Any, in_deriv: Any, nlist: Any, axis: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_force_se_a_grad(grad: Any, net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_force_se_a_mask_grad(grad: Any, net_deriv: Any, in_deriv: Any, mask: Any, nlist: Any, total_atom_num: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
mask – A Tensor of type int32.
nlist – A Tensor of type int32.
total_atom_num – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_force_se_r_grad(grad: Any, net_deriv: Any, in_deriv: Any, nlist: Any, natoms: Any, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_virial_grad(grad: Any, net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, axis: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
axis – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_virial_se_a_grad(grad: Any, net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.prod_virial_se_r_grad(grad: Any, net_deriv: Any, in_deriv: Any, rij: Any, nlist: Any, natoms: Any, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
net_deriv – A Tensor. Must have the same type as grad.
in_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.soft_min_force_grad(grad: Any, du: Any, sw_deriv: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
du – A Tensor. Must have the same type as grad.
sw_deriv – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
- deepmd.env.op_grads_module.soft_min_virial_grad(grad: Any, du: Any, sw_deriv: Any, rij: Any, nlist: Any, natoms: Any, n_a_sel: int, n_r_sel: int, name=None) Any
TODO: add doc.
- Parameters
grad – A Tensor. Must be one of the following types: float32, float64.
du – A Tensor. Must have the same type as grad.
sw_deriv – A Tensor. Must have the same type as grad.
rij – A Tensor. Must have the same type as grad.
nlist – A Tensor of type int32.
natoms – A Tensor of type int32.
n_a_sel – An int.
n_r_sel – An int.
name – A name for the operation (optional).
- Returns
A Tensor. Has the same type as grad.
C++ API
Class Hierarchy
File Hierarchy
Full API
Namespaces
Namespace tensorflow
Classes and Structs
Struct deepmd_exception
Defined in File common.h
Inheritance Relationships
public deepmd::tf_exception(Struct tf_exception)
Struct Documentation
- struct deepmd_exception
Subclassed by deepmd::tf_exception
Struct NeighborListData
Defined in File common.h
Struct Documentation
- struct NeighborListData
Public Functions
- void copy_from_nlist(const InputNlist &inlist)
- void shuffle(const std::vector<int> &fwd_map)
- void shuffle_exclude_empty(const std::vector<int> &fwd_map)
- void make_inlist(InputNlist &inlist)
Public Members
- std::vector<int> ilist
Array stores the core region atom’s index.
- std::vector<std::vector<int>> jlist
Array stores the core region atom’s neighbor index.
- std::vector<int> numneigh
Array stores the number of neighbors of core region atoms.
- std::vector<int*> firstneigh
Array stores the the location of the first neighbor of core region atoms.
- void copy_from_nlist(const InputNlist &inlist)
Struct tf_exception
Defined in File common.h
Inheritance Relationships
public deepmd_exception(Struct deepmd_exception)
Struct Documentation
- struct tf_exception : public deepmd_exception
Throw exception if TensorFlow doesn’t work.
Class AtomMap
Defined in File AtomMap.h
Class Documentation
- class AtomMap
Public Functions
- AtomMap()
- AtomMap(const std::vector<int>::const_iterator in_begin, const std::vector<int>::const_iterator in_end)
- template<typename VALUETYPE>
void forward(typename std::vector<VALUETYPE>::iterator out, const typename std::vector<VALUETYPE>::const_iterator in, const int stride = 1, const int nframes = 1, const int nall = 0) const
- template<typename VALUETYPE>
void backward(typename std::vector<VALUETYPE>::iterator out, const typename std::vector<VALUETYPE>::const_iterator in, const int stride = 1, const int nframes = 1, const int nall = 0) const
- inline const std::vector<int> &get_type() const
- inline const std::vector<int> &get_fwd_map() const
- inline const std::vector<int> &get_bkw_map() const
- AtomMap()
Class DeepPot
Defined in File DeepPot.h
Class Documentation
- class DeepPot
Deep Potential to automatically switch backends.
Unnamed Group
- template<typename VALUETYPE>
void compute(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Unnamed Group
- template<typename VALUETYPE>
void compute(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Unnamed Group
- template<typename VALUETYPE>
void compute(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Unnamed Group
- template<typename VALUETYPE>
void compute(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Unnamed Group
- template<typename VALUETYPE>
void compute_mixed_type(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, and virial with the mixed type by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The array should be of size nframes x natoms.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute_mixed_type(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Unnamed Group
- template<typename VALUETYPE>
void compute_mixed_type(ENERGYTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, and virial with the mixed type by using this DP.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The array should be of size nframes x natoms.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
void compute_mixed_type(std::vector<ENERGYTYPE> &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>())
Public Functions
- DeepPot()
DP constructor without initialization.
- ~DeepPot()
- DeepPot(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
DP constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- void init(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
Initialize the DP.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- void print_summary(const std::string &pre) const
Print the DP summary to the screen.
- Parameters
pre – [in] The prefix to each line.
- double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- int numb_types() const
Get the number of types.
- Returns
The number of types.
- int numb_types_spin() const
Get the number of types with spin.
- Returns
The number of types with spin.
- int dim_fparam() const
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- int dim_aparam() const
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- bool is_aparam_nall() const
Get whether the atom dimension of aparam is nall instead of fparam.
- Parameters
aparam_nall – [out] whether the atom dimension of aparam is nall instead of fparam.
- template<typename VALUETYPE>
Class DeepPotBase
Defined in File DeepPot.h
Inheritance Relationships
public deepmd::DeepPotTF(Class DeepPotTF)
Class Documentation
- class DeepPotBase
Deep Potential.
Subclassed by deepmd::DeepPotTF
Unnamed Group
- virtual void computew(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>()) = 0
Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
Note
The double precision interface is used by i-PI, GROMACS, ABACUS, and CP2k.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>()) = 0
Unnamed Group
- virtual void computew(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>()) = 0
Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
Note
The double precision interface is used by LAMMPS and AMBER.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>()) = 0
Unnamed Group
- virtual void computew_mixed_type(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const int &nframes, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>()) = 0
Evaluate the energy, force, and virial with the mixed type by using this DP.
Note
At this time, no external program uses this interface.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The array should be of size nframes x natoms.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew_mixed_type(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const int &nframes, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>()) = 0
Public Functions
- inline DeepPotBase()
DP constructor without initialization.
- inline virtual ~DeepPotBase()
- DeepPotBase(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
DP constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "") = 0
Initialize the DP.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- virtual double cutoff() const = 0
Get the cutoff radius.
- Returns
The cutoff radius.
- virtual int numb_types() const = 0
Get the number of types.
- Returns
The number of types.
- virtual int numb_types_spin() const = 0
Get the number of types with spin.
- Returns
The number of types with spin.
- virtual int dim_fparam() const = 0
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- virtual int dim_aparam() const = 0
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- virtual void get_type_map(std::string &type_map) = 0
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- virtual bool is_aparam_nall() const = 0
Get whether the atom dimension of aparam is nall instead of fparam.
- Parameters
aparam_nall – [out] whether the atom dimension of aparam is nall instead of fparam.
- virtual void computew(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>()) = 0
Class DeepPotModelDevi
Defined in File DeepPot.h
Class Documentation
- class DeepPotModelDevi
Public Functions
- DeepPotModelDevi()
DP model deviation constructor without initialization.
- ~DeepPotModelDevi()
- DeepPotModelDevi(const std::vector<std::string> &models, const int &gpu_rank = 0, const std::vector<std::string> &file_contents = std::vector<std::string>())
DP model deviation constructor with initialization.
- Parameters
models – [in] The names of the frozen model files.
gpu_rank – [in] The GPU rank. Default is 0.
file_contents – [in] The contents of the model files. If it is not empty, DP will read from the strings instead of the files.
- void init(const std::vector<std::string> &models, const int &gpu_rank = 0, const std::vector<std::string> &file_contents = std::vector<std::string>())
Initialize the DP model deviation contrcutor.
- Parameters
models – [in] The names of the frozen model files.
gpu_rank – [in] The GPU rank. Default is 0.
file_contents – [in] The contents of the model files. If it is not empty, DP will read from the strings instead of the files.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &all_ener, std::vector<std::vector<VALUETYPE>> &all_force, std::vector<std::vector<VALUETYPE>> &all_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using these DP models.
- Parameters
all_ener – [out] The system energies of all models.
all_force – [out] The forces on each atom of all models.
all_virial – [out] The virials of all models.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. dim_aparam. Then all frames and atoms are provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &all_ener, std::vector<std::vector<VALUETYPE>> &all_force, std::vector<std::vector<VALUETYPE>> &all_virial, std::vector<std::vector<VALUETYPE>> &all_atom_energy, std::vector<std::vector<VALUETYPE>> &all_atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using these DP models.
- Parameters
all_ener – [out] The system energies of all models.
all_force – [out] The forces on each atom of all models.
all_virial – [out] The virials of all models.
all_atom_energy – [out] The atomic energies of all models.
all_atom_virial – [out] The atomic virials of all models.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. dim_aparam. Then all frames and atoms are provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &all_ener, std::vector<std::vector<VALUETYPE>> &all_force, std::vector<std::vector<VALUETYPE>> &all_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using these DP models.
- Parameters
all_ener – [out] The system energies of all models.
all_force – [out] The forces on each atom of all models.
all_virial – [out] The virials of all models.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. dim_aparam. Then all frames and atoms are provided with the same aparam.
- template<typename VALUETYPE>
void compute(std::vector<ENERGYTYPE> &all_ener, std::vector<std::vector<VALUETYPE>> &all_force, std::vector<std::vector<VALUETYPE>> &all_virial, std::vector<std::vector<VALUETYPE>> &all_atom_energy, std::vector<std::vector<VALUETYPE>> &all_atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using these DP models.
- Parameters
all_ener – [out] The system energies of all models.
all_force – [out] The forces on each atom of all models.
all_virial – [out] The virials of all models.
all_atom_energy – [out] The atomic energies of all models.
all_atom_virial – [out] The atomic virials of all models.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam. dim_aparam. Then all frames and atoms are provided with the same aparam.
- inline double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline int numb_types_spin() const
Get the number of types with spin.
- Returns
The number of types with spin.
- inline int dim_fparam() const
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- inline int dim_aparam() const
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- template<typename VALUETYPE>
void compute_avg(VALUETYPE &dener, const std::vector<VALUETYPE> &all_energy) Compute the average energy.
- Parameters
dener – [out] The average energy.
all_energy – [in] The energies of all models.
- template<typename VALUETYPE>
void compute_avg(std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx) Compute the average of vectors.
- Parameters
avg – [out] The average of vectors.
xx – [in] The vectors of all models.
- template<typename VALUETYPE>
void compute_std(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx, const int &stride) Compute the standard deviation of vectors.
- Parameters
std – [out] The standard deviation of vectors.
avg – [in] The average of vectors.
xx – [in] The vectors of all models.
stride – [in] The stride to compute the deviation.
- template<typename VALUETYPE>
void compute_relative_std(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const VALUETYPE eps, const int &stride) Compute the relative standard deviation of vectors.
- Parameters
std – [out] The standard deviation of vectors.
avg – [in] The average of vectors.
eps – [in] The level parameter for computing the deviation.
stride – [in] The stride to compute the deviation.
- template<typename VALUETYPE>
void compute_std_e(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx) Compute the standard deviation of atomic energies.
- Parameters
std – [out] The standard deviation of atomic energies.
avg – [in] The average of atomic energies.
xx – [in] The vectors of all atomic energies.
- template<typename VALUETYPE>
void compute_std_f(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx) Compute the standard deviation of forces.
- Parameters
std – [out] The standard deviation of forces.
avg – [in] The average of forces.
xx – [in] The vectors of all forces.
- template<typename VALUETYPE>
void compute_relative_std_f(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const VALUETYPE eps) Compute the relative standard deviation of forces.
- Parameters
std – [out] The relative standard deviation of forces.
avg – [in] The relative average of forces.
eps – [in] The level parameter for computing the deviation.
- inline bool is_aparam_nall() const
Get whether the atom dimension of aparam is nall instead of fparam.
- Parameters
aparam_nall – [out] whether the atom dimension of aparam is nall instead of fparam.
- DeepPotModelDevi()
Class DeepPotTF
Defined in File DeepPotTF.h
Inheritance Relationships
public deepmd::DeepPotBase(Class DeepPotBase)
Class Documentation
- class DeepPotTF : public deepmd::DeepPotBase
TensorFlow implementation for Deep Potential.
Public Functions
- DeepPotTF()
DP constructor without initialization.
- ~DeepPotTF()
- DeepPotTF(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
DP constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
Initialize the DP.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
file_content – [in] The content of the model file. If it is not empty, DP will read from the string instead of the file.
- inline virtual double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline virtual int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline virtual int numb_types_spin() const
Get the number of types with spin.
- Returns
The number of types with spin.
- inline virtual int dim_fparam() const
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- inline virtual int dim_aparam() const
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- virtual void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- inline virtual bool is_aparam_nall() const
Get whether the atom dimension of aparam is nall instead of fparam.
- Parameters
aparam_nall – [out] whether the atom dimension of aparam is nall instead of fparam.
- virtual void computew(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>())
Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
Note
The double precision interface is used by i-PI, GROMACS, ABACUS, and CP2k.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>())
- virtual void computew(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>())
Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
Note
The double precision interface is used by LAMMPS and AMBER.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The input neighbour list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const int nghost, const InputNlist &inlist, const int &ago, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>())
- virtual void computew_mixed_type(std::vector<double> &ener, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_energy, std::vector<double> &atom_virial, const int &nframes, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const std::vector<double> &fparam = std::vector<double>(), const std::vector<double> &aparam = std::vector<double>())
Evaluate the energy, force, and virial with the mixed type by using this DP.
Note
At this time, no external program uses this interface.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The array should be of size nframes x natoms.
box – [in] The cell of the region. The array should be of size nframes x 9.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- virtual void computew_mixed_type(std::vector<double> &ener, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_energy, std::vector<float> &atom_virial, const int &nframes, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const std::vector<float> &fparam = std::vector<float>(), const std::vector<float> &aparam = std::vector<float>())
- DeepPotTF()
Class DeepTensor
Defined in File DeepTensor.h
Class Documentation
- class DeepTensor
Deep Tensor.
Public Functions
- DeepTensor()
Deep Tensor constructor without initialization.
- ~DeepTensor()
- DeepTensor(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Deep Tensor constructor with initialization..
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the Deep Tensor.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- void print_summary(const std::string &pre) const
Print the DP summary to the screen.
- Parameters
pre – [in] The prefix to each line.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &value, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the value by using this model.
- Parameters
value – [out] The value to evalute, usually would be the atomic tensor.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &value, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &inlist) Evaluate the value by using this model.
- Parameters
value – [out] The value to evalute, usually would be the atomic tensor.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &inlist) Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_tensor, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_tensor, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &inlist) Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
- double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- int numb_types() const
Get the number of types.
- Returns
The number of types.
- int output_dim() const
Get the output dimension.
- Returns
The output dimension.
- const std::vector<int> &sel_types() const
Get the list of sel types.
- Returns
The list of sel types.
- void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- DeepTensor()
Class DeepTensorBase
Defined in File DeepTensor.h
Inheritance Relationships
public deepmd::DeepTensorTF(Class DeepTensorTF)
Class Documentation
- class DeepTensorBase
Deep Tensor.
Subclassed by deepmd::DeepTensorTF
Unnamed Group
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const bool request_deriv) = 0
Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
request_deriv – [in] Whether to request the derivative of the global tensor, including force and virial.
- virtual void computew(std::vector<float> &global_tensor, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_tensor, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const bool request_deriv) = 0
Unnamed Group
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const int nghost, const InputNlist &inlist, const bool request_deriv) = 0
Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
request_deriv – [in] Whether to request the derivative of the global tensor, including force and virial.
- virtual void computew(std::vector<float> &global_tensor, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_tensor, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const int nghost, const InputNlist &inlist, const bool request_deriv) = 0
Public Functions
- inline DeepTensorBase()
Deep Tensor constructor without initialization.
- inline virtual ~DeepTensorBase()
- DeepTensorBase(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Deep Tensor constructor with initialization..
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "") = 0
Initialize the Deep Tensor.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- virtual double cutoff() const = 0
Get the cutoff radius.
- Returns
The cutoff radius.
- virtual int numb_types() const = 0
Get the number of types.
- Returns
The number of types.
- virtual int output_dim() const = 0
Get the output dimension.
- Returns
The output dimension.
- virtual const std::vector<int> &sel_types() const = 0
Get the list of sel types.
- Returns
The list of sel types.
- virtual void get_type_map(std::string &type_map) = 0
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const bool request_deriv) = 0
Class DeepTensorTF
Defined in File DeepTensorTF.h
Inheritance Relationships
public deepmd::DeepTensorBase(Class DeepTensorBase)
Class Documentation
- class DeepTensorTF : public deepmd::DeepTensorBase
Deep Tensor.
Unnamed Group
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const bool request_deriv)
Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
request_deriv – [in] Whether to request the derivative of the global tensor, including force and virial.
- virtual void computew(std::vector<float> &global_tensor, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_tensor, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const bool request_deriv)
Unnamed Group
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const int nghost, const InputNlist &inlist, const bool request_deriv)
Evaluate the global tensor and component-wise force and virial.
- Parameters
global_tensor – [out] The global tensor to evalute.
force – [out] The component-wise force of the global tensor, size odim x natoms x 3.
virial – [out] The component-wise virial of the global tensor, size odim x 9.
atom_tensor – [out] The atomic tensor value of the model, size natoms x odim.
atom_virial – [out] The component-wise atomic virial of the global tensor, size odim x natoms x 9.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9.
nghost – [in] The number of ghost atoms.
inlist – [in] The input neighbour list.
request_deriv – [in] Whether to request the derivative of the global tensor, including force and virial.
- virtual void computew(std::vector<float> &global_tensor, std::vector<float> &force, std::vector<float> &virial, std::vector<float> &atom_tensor, std::vector<float> &atom_virial, const std::vector<float> &coord, const std::vector<int> &atype, const std::vector<float> &box, const int nghost, const InputNlist &inlist, const bool request_deriv)
Public Functions
- DeepTensorTF()
Deep Tensor constructor without initialization.
- ~DeepTensorTF()
- DeepTensorTF(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Deep Tensor constructor with initialization..
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the Deep Tensor.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] Name scopes of operations.
- inline virtual double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline virtual int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline virtual int output_dim() const
Get the output dimension.
- Returns
The output dimension.
- inline virtual const std::vector<int> &sel_types() const
Get the list of sel types.
- Returns
The list of sel types.
- virtual void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- virtual void computew(std::vector<double> &global_tensor, std::vector<double> &force, std::vector<double> &virial, std::vector<double> &atom_tensor, std::vector<double> &atom_virial, const std::vector<double> &coord, const std::vector<int> &atype, const std::vector<double> &box, const bool request_deriv)
Class DipoleChargeModifier
Defined in File DataModifier.h
Class Documentation
- class DipoleChargeModifier
Dipole charge modifier.
Public Functions
- DipoleChargeModifier()
Dipole charge modifier without initialization.
- DipoleChargeModifier(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Dipole charge modifier without initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- ~DipoleChargeModifier()
- void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the dipole charge modifier.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- void print_summary(const std::string &pre) const
Print the DP summary to the screen.
- Parameters
pre – [in] The prefix to each line.
- template<typename VALUETYPE>
void compute(std::vector<VALUETYPE> &dfcorr_, std::vector<VALUETYPE> &dvcorr_, const std::vector<VALUETYPE> &dcoord_, const std::vector<int> &datype_, const std::vector<VALUETYPE> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<VALUETYPE> &delef_, const int nghost, const InputNlist &lmp_list) Evaluate the force and virial correction by using this dipole charge modifier.
- Parameters
dfcorr_ – [out] The force correction on each atom.
dvcorr_ – [out] The virial correction.
dcoord_ – [in] The coordinates of atoms. The array should be of size nall x 3.
datype_ – [in] The atom types. The list should contain nall ints.
dbox – [in] The cell of the region. The array should be of size 9.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
delef_ – [in] The electric field on each atom. The array should be of size nloc x 3.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The neighbor list.
- double cutoff() const
Get cutoff radius.
- Returns
double cutoff radius.
- int numb_types() const
Get the number of atom types.
- Returns
int number of atom types.
- const std::vector<int> &sel_types() const
Get the list of sel types.
- Returns
The list of sel types.
- DipoleChargeModifier()
Class DipoleChargeModifierBase
Defined in File DataModifier.h
Inheritance Relationships
public deepmd::DipoleChargeModifierTF(Class DipoleChargeModifierTF)
Class Documentation
- class DipoleChargeModifierBase
Dipole charge modifier. (Base class)
Subclassed by deepmd::DipoleChargeModifierTF
Unnamed Group
- virtual void computew(std::vector<double> &dfcorr_, std::vector<double> &dvcorr_, const std::vector<double> &dcoord_, const std::vector<int> &datype_, const std::vector<double> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<double> &delef_, const int nghost, const InputNlist &lmp_list) = 0
Evaluate the force and virial correction by using this dipole charge modifier.
- Parameters
dfcorr_ – [out] The force correction on each atom.
dvcorr_ – [out] The virial correction.
dcoord_ – [in] The coordinates of atoms. The array should be of size natoms x 3.
datype_ – [in] The atom types. The list should contain natoms ints.
dbox – [in] The cell of the region. The array should be of size 9.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
delef_ – [in] The electric field on each atom. The array should be of size natoms x 3.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The neighbor list.
- virtual void computew(std::vector<float> &dfcorr_, std::vector<float> &dvcorr_, const std::vector<float> &dcoord_, const std::vector<int> &datype_, const std::vector<float> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<float> &delef_, const int nghost, const InputNlist &lmp_list) = 0
Public Functions
- inline DipoleChargeModifierBase()
Dipole charge modifier without initialization.
- DipoleChargeModifierBase(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Dipole charge modifier without initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- inline virtual ~DipoleChargeModifierBase()
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "") = 0
Initialize the dipole charge modifier.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- virtual double cutoff() const = 0
Get cutoff radius.
- Returns
double cutoff radius.
- virtual int numb_types() const = 0
Get the number of atom types.
- Returns
int number of atom types.
- virtual const std::vector<int> &sel_types() const = 0
Get the list of sel types.
- Returns
The list of sel types.
- virtual void computew(std::vector<double> &dfcorr_, std::vector<double> &dvcorr_, const std::vector<double> &dcoord_, const std::vector<int> &datype_, const std::vector<double> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<double> &delef_, const int nghost, const InputNlist &lmp_list) = 0
Class DipoleChargeModifierTF
Defined in File DataModifierTF.h
Inheritance Relationships
public deepmd::DipoleChargeModifierBase(Class DipoleChargeModifierBase)
Class Documentation
- class DipoleChargeModifierTF : public deepmd::DipoleChargeModifierBase
Dipole charge modifier.
Public Functions
- DipoleChargeModifierTF()
Dipole charge modifier without initialization.
- DipoleChargeModifierTF(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Dipole charge modifier without initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- ~DipoleChargeModifierTF()
- virtual void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the dipole charge modifier.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank. Default is 0.
name_scope – [in] The name scope.
- inline virtual double cutoff() const
Get cutoff radius.
- Returns
double cutoff radius.
- inline virtual int numb_types() const
Get the number of atom types.
- Returns
int number of atom types.
- inline virtual const std::vector<int> &sel_types() const
Get the list of sel types.
- Returns
The list of sel types.
- virtual void computew(std::vector<double> &dfcorr_, std::vector<double> &dvcorr_, const std::vector<double> &dcoord_, const std::vector<int> &datype_, const std::vector<double> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<double> &delef_, const int nghost, const InputNlist &lmp_list)
Evaluate the force and virial correction by using this dipole charge modifier.
- Parameters
dfcorr_ – [out] The force correction on each atom.
dvcorr_ – [out] The virial correction.
dcoord_ – [in] The coordinates of atoms. The array should be of size natoms x 3.
datype_ – [in] The atom types. The list should contain natoms ints.
dbox – [in] The cell of the region. The array should be of size 9.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
delef_ – [in] The electric field on each atom. The array should be of size natoms x 3.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The neighbor list.
- virtual void computew(std::vector<float> &dfcorr_, std::vector<float> &dvcorr_, const std::vector<float> &dcoord_, const std::vector<int> &datype_, const std::vector<float> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<float> &delef_, const int nghost, const InputNlist &lmp_list)
- DipoleChargeModifierTF()
Enums
Functions
Function deepmd::check_status
Defined in File common.h
Function Documentation
- void deepmd::check_status(const tensorflow::Status &status)
Check TensorFlow status. Exit if not OK.
- Parameters
status – [in] TensorFlow status.
Function deepmd::convert_pbtxt_to_pb
Defined in File common.h
Function Documentation
- void deepmd::convert_pbtxt_to_pb(std::string fn_pb_txt, std::string fn_pb)
Convert pbtxt to pb.
- Parameters
fn_pb_txt – [in] Filename of the pb txt file.
fn_pb – [in] Filename of the pb file.
Function deepmd::get_env_nthreads
Defined in File common.h
Function Documentation
- void deepmd::get_env_nthreads(int &num_intra_nthreads, int &num_inter_nthreads)
Get the number of threads from the environment variable.
A warning will be thrown if environmental variables are not set.
- Parameters
num_intra_nthreads – [out] The number of intra threads. Read from TF_INTRA_OP_PARALLELISM_THREADS.
num_inter_nthreads – [out] The number of inter threads. Read from TF_INTER_OP_PARALLELISM_THREADS.
Function deepmd::load_op_library
Defined in File common.h
Function Documentation
- void deepmd::load_op_library()
Dynamically load OP library. This should be called before loading graphs.
Function deepmd::model_compatable
Defined in File common.h
Function Documentation
- bool deepmd::model_compatable(std::string &model_version)
Check if the model version is supported.
- Parameters
model_version – [in] The model version.
- Returns
Whether the model is supported (true or false).
Function deepmd::name_prefix
Defined in File common.h
Function Documentation
- std::string deepmd::name_prefix(const std::string &name_scope)
Function deepmd::print_summary
Defined in File common.h
Function Documentation
- void deepmd::print_summary(const std::string &pre)
Print the summary of DeePMD-kit, including the version and the build information.
- Parameters
pre – [in] The prefix to each line.
Function deepmd::read_file_to_string
Defined in File common.h
Function Documentation
- void deepmd::read_file_to_string(std::string model, std::string &file_content)
Read model file to a string.
- Parameters
model – [in] Path to the model.
file_content – [out] Content of the model file.
Template Function deepmd::select_by_type
Defined in File common.h
Function Documentation
- template<typename VALUETYPE>
void deepmd::select_by_type(std::vector<int> &fwd_map, std::vector<int> &bkw_map, int &nghost_real, const std::vector<VALUETYPE> &dcoord_, const std::vector<int> &datype_, const int &nghost, const std::vector<int> &sel_type_) Get forward and backward map of selected atoms by atom types.
- Parameters
fwd_map – [out] The forward map with size natoms.
bkw_map – [out] The backward map with size nreal.
nghost_real – [out] The number of selected ghost atoms.
dcoord_ – [in] The coordinates of all atoms. Reserved for compatibility.
datype_ – [in] The atom types of all atoms.
nghost – [in] The number of ghost atoms.
sel_type_ – [in] The selected atom types.
Template Function deepmd::select_map(std::vector<VT>&, const std::vector<VT>&, const std::vector<int>&, const int&, const int&, const int&, const int&)
Defined in File common.h
Function Documentation
- template<typename VT>
void deepmd::select_map(std::vector<VT> &out, const std::vector<VT> &in, const std::vector<int> &fwd_map, const int &stride, const int &nframes = 1, const int &nall1 = 0, const int &nall2 = 0) Apply the given map to a vector.
- Parameters
out – [out] The output vector.
in – [in] The input vector.
fwd_map – [in] The map.
stride – [in] The stride of the input vector.
nframes – [in] The number of frames.
nall1 – [in] The number of atoms in the input vector.
nall2 – [in] The number of atoms in the output vector.
Template Function deepmd::select_map(typename std::vector<VT>::iterator, const typename std::vector<VT>::const_iterator, const std::vector<int>&, const int&, const int&, const int&, const int&)
Defined in File common.h
Function Documentation
- template<typename VT>
void deepmd::select_map(typename std::vector<VT>::iterator out, const typename std::vector<VT>::const_iterator in, const std::vector<int> &fwd_map, const int &stride, const int &nframes = 1, const int &nall1 = 0, const int &nall2 = 0) Apply the given map to a vector.
- Parameters
out – [out] The output vector.
in – [in] The input vector.
fwd_map – [in] The map.
stride – [in] The stride of the input vector.
nframes – [in] The number of frames.
nall1 – [in] The number of atoms in the input vector.
nall2 – [in] The number of atoms in the output vector.
Template Function deepmd::select_map_inv(std::vector<VT>&, const std::vector<VT>&, const std::vector<int>&, const int&)
Defined in File common.h
Function Documentation
Template Function deepmd::select_map_inv(typename std::vector<VT>::iterator, const typename std::vector<VT>::const_iterator, const std::vector<int>&, const int&)
Defined in File common.h
Function Documentation
Template Function deepmd::select_real_atoms
Defined in File common.h
Function Documentation
Template Function deepmd::select_real_atoms_coord
Defined in File common.h
Function Documentation
- template<typename VALUETYPE>
void deepmd::select_real_atoms_coord(std::vector<VALUETYPE> &dcoord, std::vector<int> &datype, std::vector<VALUETYPE> &aparam, int &nghost_real, std::vector<int> &fwd_map, std::vector<int> &bkw_map, int &nall_real, int &nloc_real, const std::vector<VALUETYPE> &dcoord_, const std::vector<int> &datype_, const std::vector<VALUETYPE> &aparam_, const int &nghost, const int &ntypes, const int &nframes, const int &daparam, const int &nall, const bool aparam_nall = false)
Function deepmd::session_get_dtype
Defined in File common.h
Function Documentation
- int deepmd::session_get_dtype(tensorflow::Session *session, const std::string name, const std::string scope = "")
Get the type of a tensor.
- Parameters
session – [in] TensorFlow session.
name – [in] The name of the tensor.
scope – [in] The scope of the tensor.
- Returns
The type of the tensor as int.
Template Function deepmd::session_get_scalar
Defined in File common.h
Function Documentation
- template<typename VT>
VT deepmd::session_get_scalar(tensorflow::Session *session, const std::string name, const std::string scope = "") Get the value of a tensor.
- Parameters
session – [in] TensorFlow session.
name – [in] The name of the tensor.
scope – [in] The scope of the tensor.
- Returns
The value of the tensor.
Template Function deepmd::session_get_vector
Defined in File common.h
Function Documentation
- template<typename VT>
void deepmd::session_get_vector(std::vector<VT> &o_vec, tensorflow::Session *session, const std::string name_, const std::string scope = "") Get the vector of a tensor.
- Parameters
o_vec – [out] The output vector.
session – [in] TensorFlow session.
name – [in] The name of the tensor.
scope – [in] The scope of the tensor.
Template Function deepmd::session_input_tensors(std::vector<std::pair<std::string, tensorflow::Tensor>>&, const std::vector<VALUETYPE>&, const int&, const std::vector<int>&, const std::vector<VALUETYPE>&, const double&, const std::vector<VALUETYPE>&, const std::vector<VALUETYPE>&, const deepmd::AtomMap&, const std::string, const bool)
Defined in File common.h
Function Documentation
- template<typename MODELTYPE, typename VALUETYPE>
int deepmd::session_input_tensors(std::vector<std::pair<std::string, tensorflow::Tensor>> &input_tensors, const std::vector<VALUETYPE> &dcoord_, const int &ntypes, const std::vector<int> &datype_, const std::vector<VALUETYPE> &dbox, const double &cell_size, const std::vector<VALUETYPE> &fparam_, const std::vector<VALUETYPE> &aparam_, const deepmd::AtomMap &atommap, const std::string scope = "", const bool aparam_nall = false) Get input tensors.
- Parameters
input_tensors – [out] Input tensors.
dcoord_ – [in] Coordinates of atoms.
ntypes – [in] Number of atom types.
datype_ – [in] Atom types.
dbox – [in] Box matrix.
cell_size – [in] Cell size.
fparam_ – [in] Frame parameters.
aparam_ – [in] Atom parameters.
atommap – [in] Atom map.
scope – [in] The scope of the tensors.
aparam_nall – [in] Whether the atomic dimesion of atomic parameters is nall.
Template Function deepmd::session_input_tensors(std::vector<std::pair<std::string, tensorflow::Tensor>>&, const std::vector<VALUETYPE>&, const int&, const std::vector<int>&, const std::vector<VALUETYPE>&, InputNlist&, const std::vector<VALUETYPE>&, const std::vector<VALUETYPE>&, const deepmd::AtomMap&, const int, const int, const std::string, const bool)
Defined in File common.h
Function Documentation
- template<typename MODELTYPE, typename VALUETYPE>
int deepmd::session_input_tensors(std::vector<std::pair<std::string, tensorflow::Tensor>> &input_tensors, const std::vector<VALUETYPE> &dcoord_, const int &ntypes, const std::vector<int> &datype_, const std::vector<VALUETYPE> &dbox, InputNlist &dlist, const std::vector<VALUETYPE> &fparam_, const std::vector<VALUETYPE> &aparam_, const deepmd::AtomMap &atommap, const int nghost, const int ago, const std::string scope = "", const bool aparam_nall = false) Get input tensors.
- Parameters
input_tensors – [out] Input tensors.
dcoord_ – [in] Coordinates of atoms.
ntypes – [in] Number of atom types.
datype_ – [in] Atom types.
dlist – [in] Neighbor list.
fparam_ – [in] Frame parameters.
aparam_ – [in] Atom parameters.
atommap – [in] Atom map.
nghost – [in] Number of ghost atoms.
ago – [in] Update the internal neighbour list if ago is 0.
scope – [in] The scope of the tensors.
aparam_nall – [in] Whether the atomic dimesion of atomic parameters is nall.
Template Function deepmd::session_input_tensors_mixed_type
Defined in File common.h
Function Documentation
- template<typename MODELTYPE, typename VALUETYPE>
int deepmd::session_input_tensors_mixed_type(std::vector<std::pair<std::string, tensorflow::Tensor>> &input_tensors, const int &nframes, const std::vector<VALUETYPE> &dcoord_, const int &ntypes, const std::vector<int> &datype_, const std::vector<VALUETYPE> &dbox, const double &cell_size, const std::vector<VALUETYPE> &fparam_, const std::vector<VALUETYPE> &aparam_, const deepmd::AtomMap &atommap, const std::string scope = "", const bool aparam_nall = false) Get input tensors for mixed type.
- Parameters
input_tensors – [out] Input tensors.
nframes – [in] Number of frames.
dcoord_ – [in] Coordinates of atoms.
ntypes – [in] Number of atom types.
datype_ – [in] Atom types.
dlist – [in] Neighbor list.
fparam_ – [in] Frame parameters.
aparam_ – [in] Atom parameters.
atommap – [in] Atom map.
nghost – [in] Number of ghost atoms.
ago – [in] Update the internal neighbour list if ago is 0.
scope – [in] The scope of the tensors.
aparam_nall – [in] Whether the atomic dimesion of atomic parameters is nall.
Typedefs
Typedef deepmd::ENERGYTYPE
Defined in File common.h
Typedef Documentation
- typedef double deepmd::ENERGYTYPE
Typedef deepmd::STRINGTYPE
Defined in File tf_private.h
Typedef Documentation
- typedef std::string deepmd::STRINGTYPE
C API
Class Hierarchy
File Hierarchy
Full API
Namespaces
Namespace std
Classes and Structs
Struct deepmd_exception
Defined in File deepmd.hpp
Inheritance Relationships
public std::runtime_error
Struct Documentation
- struct deepmd_exception : public std::runtime_error
General DeePMD-kit exception. Throw if anything doesn’t work.
Struct InputNlist
Defined in File deepmd.hpp
Struct Documentation
Struct DP_DeepPot
Defined in File c_api_internal.h
Struct Documentation
- struct DP_DeepPot
Struct DP_DeepPotModelDevi
Defined in File c_api_internal.h
Struct Documentation
- struct DP_DeepPotModelDevi
Struct DP_DeepTensor
Defined in File c_api_internal.h
Struct Documentation
- struct DP_DeepTensor
Struct DP_DipoleChargeModifier
Defined in File c_api_internal.h
Struct Documentation
- struct DP_DipoleChargeModifier
Public Functions
- DP_DipoleChargeModifier()
- DP_DipoleChargeModifier(deepmd::DipoleChargeModifier &dcm)
- DP_DipoleChargeModifier()
Struct DP_Nlist
Defined in File c_api_internal.h
Struct Documentation
- struct DP_Nlist
Class DeepPot
Defined in File deepmd.hpp
Class Documentation
- class DeepPot
Deep Potential.
Public Functions
- inline DeepPot()
DP constructor without initialization.
- inline ~DeepPot()
- inline DeepPot(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
DP constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank.
file_content – [in] The content of the frozen model file.
- inline void init(const std::string &model, const int &gpu_rank = 0, const std::string &file_content = "")
Initialize the DP.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank.
file_content – [in] The content of the frozen model file.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP.
Warning
Natoms should not be zero when computing multiple frames.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP.
Warning
Natoms should not be zero when computing multiple frames.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP with the neighbor list.
Warning
Natoms should not be zero when computing multiple frames.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP with the neighbor list.
Warning
Natoms should not be zero when computing multiple frames.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute_mixed_type(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP with the mixed type.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE, typename ENERGYVTYPE>
inline void compute_mixed_type(ENERGYVTYPE &ener, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_energy, std::vector<VALUETYPE> &atom_virial, const int &nframes, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP with the mixed type.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
nframes – [in] The number of frames.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- inline double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline int numb_types_spin() const
Get the number of types with spin.
- Returns
The number of types with spin.
- inline void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- inline void print_summary(const std::string &pre) const
Print the summary of DeePMD-kit, including the version and the build information.
- Parameters
pre – [in] The prefix to each line.
- inline int dim_fparam() const
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- inline int dim_aparam() const
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- inline DeepPot()
Class DeepPotModelDevi
Defined in File deepmd.hpp
Class Documentation
- class DeepPotModelDevi
Deep Potential model deviation.
Public Functions
- inline DeepPotModelDevi()
DP model deviation constructor without initialization.
- inline ~DeepPotModelDevi()
- inline DeepPotModelDevi(const std::vector<std::string> &models)
DP model deviation constructor with initialization.
- Parameters
models – [in] The names of the frozen model file.
- inline void init(const std::vector<std::string> &models, const int &gpu_rank = 0, const std::vector<std::string> &file_content = std::vector<std::string>())
Initialize the DP model deviation.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The GPU rank.
file_content – [in] The content of the frozen model file.
- template<typename VALUETYPE>
inline void compute(std::vector<double> &ener, std::vector<std::vector<VALUETYPE>> &force, std::vector<std::vector<VALUETYPE>> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP model deviation.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
inline void compute(std::vector<double> &ener, std::vector<std::vector<VALUETYPE>> &force, std::vector<std::vector<VALUETYPE>> &virial, std::vector<std::vector<VALUETYPE>> &atom_energy, std::vector<std::vector<VALUETYPE>> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP model deviation.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
inline void compute(std::vector<double> &ener, std::vector<std::vector<VALUETYPE>> &force, std::vector<std::vector<VALUETYPE>> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force and virial by using this DP model deviation.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- template<typename VALUETYPE>
inline void compute(std::vector<double> &ener, std::vector<std::vector<VALUETYPE>> &force, std::vector<std::vector<VALUETYPE>> &virial, std::vector<std::vector<VALUETYPE>> &atom_energy, std::vector<std::vector<VALUETYPE>> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list, const int &ago, const std::vector<VALUETYPE> &fparam = std::vector<VALUETYPE>(), const std::vector<VALUETYPE> &aparam = std::vector<VALUETYPE>()) Evaluate the energy, force, virial, atomic energy, and atomic virial by using this DP model deviation.
- Parameters
ener – [out] The system energy.
force – [out] The force on each atom.
virial – [out] The virial.
atom_energy – [out] The atomic energy.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameter. The array can be of size : nframes x dim_fparam. dim_fparam. Then all frames are assumed to be provided with the same fparam.
aparam – [in] The atomic parameter The array can be of size : nframes x natoms x dim_aparam. natoms x dim_aparam. Then all frames are assumed to be provided with the same aparam.
- inline double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline int numb_types_spin() const
Get the number of types with spin.
- Returns
The number of types with spin.
- inline int dim_fparam() const
Get the dimension of the frame parameter.
- Returns
The dimension of the frame parameter.
- inline int dim_aparam() const
Get the dimension of the atomic parameter.
- Returns
The dimension of the atomic parameter.
- template<typename VALUETYPE>
inline void compute_avg(std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx) Compute the average of vectors.
- Parameters
avg – [out] The average of vectors.
xx – [in] The vectors of all models.
- template<typename VALUETYPE>
inline void compute_std(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx, const int &stride) Compute the standard deviation of vectors.
- Parameters
std – [out] The standard deviation of vectors.
avg – [in] The average of vectors.
xx – [in] The vectors of all models.
stride – [in] The stride to compute the deviation.
- template<typename VALUETYPE>
inline void compute_relative_std(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const VALUETYPE eps, const int &stride) Compute the relative standard deviation of vectors.
- Parameters
std – [out] The standard deviation of vectors.
avg – [in] The average of vectors.
eps – [in] The level parameter for computing the deviation.
stride – [in] The stride to compute the deviation.
- template<typename VALUETYPE>
inline void compute_std_f(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const std::vector<std::vector<VALUETYPE>> &xx) Compute the standard deviation of forces.
- Parameters
std – [out] The standard deviation of forces.
avg – [in] The average of forces.
xx – [in] The vectors of all forces.
- template<typename VALUETYPE>
inline void compute_relative_std_f(std::vector<VALUETYPE> &std, const std::vector<VALUETYPE> &avg, const VALUETYPE eps) Compute the relative standard deviation of forces.
- Parameters
std – [out] The relative standard deviation of forces.
avg – [in] The relative average of forces.
eps – [in] The level parameter for computing the deviation.
- inline DeepPotModelDevi()
Class DeepTensor
Defined in File deepmd.hpp
Class Documentation
- class DeepTensor
Deep Tensor.
Public Functions
- inline DeepTensor()
Deep Tensor constructor without initialization.
- inline ~DeepTensor()
- inline DeepTensor(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
DeepTensor constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
- inline void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the DeepTensor.
- Parameters
model – [in] The name of the frozen model file.
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &tensor, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the tensor, force and virial by using this Deep Tensor.
- Parameters
tensor – [out] The atomic tensor.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &tensor, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list) Evaluate the tensor, force and virial by using this Deep Tensor with the neighbor list.
- Parameters
tensor – [out] The tensor.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the global tensor, force and virial by using this Deep Tensor.
- Parameters
global_tensor – [out] The global tensor.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_tensor, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box) Evaluate the global tensor, force, virial, atomic tensor, and atomic virial by using this Deep Tensor.
- Parameters
global_tensor – [out] The global tensor.
force – [out] The force on each atom.
virial – [out] The virial.
atom_tensor – [out] The atomic tensor.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list) Evaluate the global tensor, force and virial by using this Deep Tensor with the neighbor list.
- Parameters
global_tensor – [out] The global tensor.
force – [out] The force on each atom.
virial – [out] The virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &global_tensor, std::vector<VALUETYPE> &force, std::vector<VALUETYPE> &virial, std::vector<VALUETYPE> &atom_tensor, std::vector<VALUETYPE> &atom_virial, const std::vector<VALUETYPE> &coord, const std::vector<int> &atype, const std::vector<VALUETYPE> &box, const int nghost, const InputNlist &lmp_list) Evaluate the global tensor, force, virial, atomic tensor, and atomic virial by using this Deep Tensor with the neighbor list.
- Parameters
global_tensor – [out] The global tensor.
force – [out] The force on each atom.
virial – [out] The virial.
atom_tensor – [out] The atomic tensor.
atom_virial – [out] The atomic virial.
coord – [in] The coordinates of atoms. The array should be of size nframes x natoms x 3.
atype – [in] The atom types. The list should contain natoms ints.
box – [in] The cell of the region. The array should be of size nframes x 9 (PBC) or empty (no PBC).
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
- inline double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline int output_dim() const
Get the output dimension.
- Returns
The output dimension.
- inline std::vector<int> sel_types() const
- inline void print_summary(const std::string &pre) const
Print the summary of DeePMD-kit, including the version and the build information.
- Parameters
pre – [in] The prefix to each line.
- inline void get_type_map(std::string &type_map)
Get the type map (element name of the atom types) of this model.
- Parameters
type_map – [out] The type map of this model.
- inline DeepTensor()
Class DipoleChargeModifier
Defined in File deepmd.hpp
Class Documentation
- class DipoleChargeModifier
Public Functions
- inline DipoleChargeModifier()
DipoleChargeModifier constructor without initialization.
- inline ~DipoleChargeModifier()
- inline DipoleChargeModifier(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
DipoleChargeModifier constructor with initialization.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The rank of the GPU to be used.
name_scope – [in] The name scope of the model.
- inline void init(const std::string &model, const int &gpu_rank = 0, const std::string &name_scope = "")
Initialize the DipoleChargeModifier.
- Parameters
model – [in] The name of the frozen model file.
gpu_rank – [in] The rank of the GPU to be used.
name_scope – [in] The name scope of the model.
- template<typename VALUETYPE>
inline void compute(std::vector<VALUETYPE> &dfcorr_, std::vector<VALUETYPE> &dvcorr_, const std::vector<VALUETYPE> &dcoord_, const std::vector<int> &datype_, const std::vector<VALUETYPE> &dbox, const std::vector<std::pair<int, int>> &pairs, const std::vector<VALUETYPE> &delef_, const int nghost, const InputNlist &lmp_list) Evaluate the force and virial correction by using this dipole charge modifier.
- Parameters
dfcorr_ – [out] The force correction on each atom.
dvcorr_ – [out] The virial correction.
dcoord_ – [in] The coordinates of atoms. The array should be of size nall x 3.
datype_ – [in] The atom types. The list should contain nall ints.
dbox – [in] The cell of the region. The array should be of size 9.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
delef_ – [in] The electric field on each atom. The array should be of size nghost x 3.
nghost – [in] The number of ghost atoms.
lmp_list – [in] The neighbor list.
- inline double cutoff() const
Get the cutoff radius.
- Returns
The cutoff radius.
- inline int numb_types() const
Get the number of types.
- Returns
The number of types.
- inline std::vector<int> sel_types() const
- inline void print_summary(const std::string &pre) const
Print the summary of DeePMD-kit, including the version and the build information.
- Parameters
pre – [in] The prefix to each line.
- inline DipoleChargeModifier()
Functions
Template Function _DP_DeepPotCompute
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepPotCompute(DP_DeepPot *dp, const int nframes, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const FPTYPE *fparam, const FPTYPE *aparam, double *energy, FPTYPE *force, FPTYPE *virial, FPTYPE *atomic_energy, FPTYPE *atomic_virial)
Specialized Template Function _DP_DeepPotCompute< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotCompute<double>(DP_DeepPot *dp, const int nframes, const int natom, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Specialized Template Function _DP_DeepPotCompute< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotCompute<float>(DP_DeepPot *dp, const int nframes, const int natom, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Template Function _DP_DeepPotComputeMixedType
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepPotComputeMixedType(DP_DeepPot *dp, const int nframes, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const FPTYPE *fparam, const FPTYPE *aparam, double *energy, FPTYPE *force, FPTYPE *virial, FPTYPE *atomic_energy, FPTYPE *atomic_virial)
Specialized Template Function _DP_DeepPotComputeMixedType< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotComputeMixedType<double>(DP_DeepPot *dp, const int nframes, const int natom, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Specialized Template Function _DP_DeepPotComputeMixedType< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotComputeMixedType<float>(DP_DeepPot *dp, const int nframes, const int natom, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Template Function _DP_DeepPotComputeNList
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepPotComputeNList(DP_DeepPot *dp, const int nframes, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const int nghost, const DP_Nlist *nlist, const int ago, const FPTYPE *fparam, const FPTYPE *aparam, double *energy, FPTYPE *force, FPTYPE *virial, FPTYPE *atomic_energy, FPTYPE *atomic_virial)
Specialized Template Function _DP_DeepPotComputeNList< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotComputeNList<double>(DP_DeepPot *dp, const int nframes, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Specialized Template Function _DP_DeepPotComputeNList< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotComputeNList<float>(DP_DeepPot *dp, const int nframes, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Template Function _DP_DeepPotModelDeviCompute
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepPotModelDeviCompute(DP_DeepPotModelDevi *dp, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const FPTYPE *fparam, const FPTYPE *aparam, double *energy, FPTYPE *force, FPTYPE *virial, FPTYPE *atomic_energy, FPTYPE *atomic_virial)
Specialized Template Function _DP_DeepPotModelDeviCompute< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotModelDeviCompute<double>(DP_DeepPotModelDevi *dp, const int natom, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Specialized Template Function _DP_DeepPotModelDeviCompute< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotModelDeviCompute<float>(DP_DeepPotModelDevi *dp, const int natom, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Template Function _DP_DeepPotModelDeviComputeNList
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepPotModelDeviComputeNList(DP_DeepPotModelDevi *dp, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const int nghost, const DP_Nlist *nlist, const int ago, const FPTYPE *fparam, const FPTYPE *aparam, double *energy, FPTYPE *force, FPTYPE *virial, FPTYPE *atomic_energy, FPTYPE *atomic_virial)
Specialized Template Function _DP_DeepPotModelDeviComputeNList< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotModelDeviComputeNList<double>(DP_DeepPotModelDevi *dp, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Specialized Template Function _DP_DeepPotModelDeviComputeNList< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepPotModelDeviComputeNList<float>(DP_DeepPotModelDevi *dp, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Template Function _DP_DeepTensorCompute
Defined in File deepmd.hpp
Function Documentation
Specialized Template Function _DP_DeepTensorCompute< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorCompute<double>(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, double *global_tensor, double *force, double *virial, double **atomic_tensor, double *atomic_virial, int *size_at)
Specialized Template Function _DP_DeepTensorCompute< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorCompute<float>(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, float *global_tensor, float *force, float *virial, float **atomic_tensor, float *atomic_virial, int *size_at)
Template Function _DP_DeepTensorComputeNList
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepTensorComputeNList(DP_DeepTensor *dt, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const int nghost, const DP_Nlist *nlist, FPTYPE *global_tensor, FPTYPE *force, FPTYPE *virial, FPTYPE **atomic_energy, FPTYPE *atomic_virial, int *size_at)
Specialized Template Function _DP_DeepTensorComputeNList< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeNList<double>(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, double *global_tensor, double *force, double *virial, double **atomic_tensor, double *atomic_virial, int *size_at)
Specialized Template Function _DP_DeepTensorComputeNList< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeNList<float>(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, float *global_tensor, float *force, float *virial, float **atomic_tensor, float *atomic_virial, int *size_at)
Template Function _DP_DeepTensorComputeTensor
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DeepTensorComputeTensor(DP_DeepTensor *dt, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, FPTYPE **tensor, int *size)
Specialized Template Function _DP_DeepTensorComputeTensor< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeTensor<double>(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, double **tensor, int *size)
Specialized Template Function _DP_DeepTensorComputeTensor< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeTensor<float>(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, float **tensor, int *size)
Template Function _DP_DeepTensorComputeTensorNList
Defined in File deepmd.hpp
Function Documentation
Specialized Template Function _DP_DeepTensorComputeTensorNList< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeTensorNList<double>(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, double **tensor, int *size)
Specialized Template Function _DP_DeepTensorComputeTensorNList< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DeepTensorComputeTensorNList<float>(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, float **tensor, int *size)
Template Function _DP_DipoleChargeModifierComputeNList
Defined in File deepmd.hpp
Function Documentation
- template<typename FPTYPE>
inline void _DP_DipoleChargeModifierComputeNList(DP_DipoleChargeModifier *dcm, const int natom, const FPTYPE *coord, const int *atype, const FPTYPE *cell, const int *pairs, const int npairs, const FPTYPE *delef_, const int nghost, const DP_Nlist *nlist, FPTYPE *dfcorr_, FPTYPE *dvcorr_)
Specialized Template Function _DP_DipoleChargeModifierComputeNList< double >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DipoleChargeModifierComputeNList<double>(DP_DipoleChargeModifier *dcm, const int natom, const double *coord, const int *atype, const double *cell, const int *pairs, const int npairs, const double *delef_, const int nghost, const DP_Nlist *nlist, double *dfcorr_, double *dvcorr_)
Specialized Template Function _DP_DipoleChargeModifierComputeNList< float >
Defined in File deepmd.hpp
Function Documentation
- template<>
inline void _DP_DipoleChargeModifierComputeNList<float>(DP_DipoleChargeModifier *dcm, const int natom, const float *coord, const int *atype, const float *cell, const int *pairs, const int npairs, const float *delef_, const int nghost, const DP_Nlist *nlist, float *dfcorr_, float *dvcorr_)
Function _DP_Get_Energy_Pointer(std::vector<double>&, const int)
Defined in File deepmd.hpp
Function Documentation
- inline double *_DP_Get_Energy_Pointer(std::vector<double> &vec, const int nframes)
Function _DP_Get_Energy_Pointer(double&, const int)
Defined in File deepmd.hpp
Function Documentation
- inline double *_DP_Get_Energy_Pointer(double &vec, const int nframes)
Function deepmd::hpp::convert_nlist
Defined in File deepmd.hpp
Function Documentation
- inline void deepmd::hpp::convert_nlist(InputNlist &to_nlist, std::vector<std::vector<int>> &from_nlist)
Convert int vector to InputNlist.
- Parameters
to_nlist – [out] InputNlist.
from_nlist – [in] 2D int vector. The first axis represents the centeral atoms and the second axis represents the neighbor atoms.
Function deepmd::hpp::convert_pbtxt_to_pb
Defined in File deepmd.hpp
Function Documentation
- inline void deepmd::hpp::convert_pbtxt_to_pb(std::string fn_pb_txt, std::string fn_pb)
Convert pbtxt to pb.
- Parameters
fn_pb_txt – [in] Filename of the pb txt file.
fn_pb – [in] Filename of the pb file.
Function deepmd::hpp::read_file_to_string
Defined in File deepmd.hpp
Function Documentation
- inline void deepmd::hpp::read_file_to_string(std::string model, std::string &file_content)
Read model file to a string.
- Parameters
model – [in] Path to the model.
file_content – [out] Content of the model file.
Template Function deepmd::hpp::select_by_type
Defined in File deepmd.hpp
Function Documentation
- template<typename VALUETYPE>
void deepmd::hpp::select_by_type(std::vector<int> &fwd_map, std::vector<int> &bkw_map, int &nghost_real, const std::vector<VALUETYPE> &dcoord_, const std::vector<int> &datype_, const int &nghost, const std::vector<int> &sel_type_) Get forward and backward map of selected atoms by atom types.
- Parameters
fwd_map – [out] The forward map with size natoms.
bkw_map – [out] The backward map with size nreal.
nghost_real – [out] The number of selected ghost atoms.
dcoord_ – [in] The coordinates of all atoms. Reserved for compatibility.
datype_ – [in] The atom types of all atoms.
nghost – [in] The number of ghost atoms.
sel_type_ – [in] The selected atom types.
Template Function deepmd::hpp::select_map
Defined in File deepmd.hpp
Function Documentation
- template<typename VT>
void deepmd::hpp::select_map(std::vector<VT> &out, const std::vector<VT> &in, const std::vector<int> &fwd_map, const int &stride) Apply the given map to a vector. Assume nframes is 1.
- Template Parameters
VT – The value type of the vector. Only support int.
- Parameters
out – [out] The output vector.
in – [in] The input vector.
fwd_map – [in] The map.
stride – [in] The stride of the input vector.
Function DP_ConvertPbtxtToPb
Defined in File c_api.h
Function Documentation
- void DP_ConvertPbtxtToPb(const char *c_pbtxt, const char *c_pb)
Convert PBtxt to PB.
- Parameters
c_pbtxt – [in] The name of the PBtxt file.
c_pb – [in] The name of the PB file.
Function DP_DeepPotCheckOK
Defined in File c_api.h
Function Documentation
- const char *DP_DeepPotCheckOK(DP_DeepPot *dp)
Check if there is any exceptions throw.
- Parameters
dp – The DP to use.
- Returns
const char* error message.
Function DP_DeepPotCompute
Defined in File c_api.h
Function Documentation
- void DP_DeepPotCompute(DP_DeepPot *dp, const int natom, const double *coord, const int *atype, const double *cell, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP. (double version)
- Attention
The number of frames is assumed to be 1.
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotCompute2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotCompute2(DP_DeepPot *dp, const int nframes, const int natom, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP. (double version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputef
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputef(DP_DeepPot *dp, const int natom, const float *coord, const int *atype, const float *cell, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP. (float version)
- Attention
The number of frames is assumed to be 1.
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputef2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputef2(DP_DeepPot *dp, const int nframes, const int natom, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP. (float version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeMixedType
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeMixedType(DP_DeepPot *dp, const int nframes, const int natoms, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP with the mixed type. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain nframes x natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeMixedTypef
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeMixedTypef(DP_DeepPot *dp, const int nframes, const int natoms, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP with the mixed type. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain nframes x natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeNList
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeNList(DP_DeepPot *dp, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP with the neighbor list. (double version)
- Attention
The number of frames is assumed to be 1.
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeNList2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeNList2(DP_DeepPot *dp, const int nframes, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP with the neighbor list. (double version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeNListf
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeNListf(DP_DeepPot *dp, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP with the neighbor list. (float version)
- Attention
The number of frames is assumed to be 1.
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotComputeNListf2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotComputeNListf2(DP_DeepPot *dp, const int nframes, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP with the neighbor list. (float version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP to use.
nframes – [in] The number of frames.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotGetCutoff
Defined in File c_api.h
Function Documentation
- double DP_DeepPotGetCutoff(DP_DeepPot *dp)
Get the type map of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The cutoff radius.
Function DP_DeepPotGetDimAParam
Defined in File c_api.h
Function Documentation
- int DP_DeepPotGetDimAParam(DP_DeepPot *dp)
Get the dimension of atomic parameters of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The dimension of atomic parameters of the DP.
Function DP_DeepPotGetDimFParam
Defined in File c_api.h
Function Documentation
- int DP_DeepPotGetDimFParam(DP_DeepPot *dp)
Get the dimension of frame parameters of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The dimension of frame parameters of the DP.
Function DP_DeepPotGetNumbTypes
Defined in File c_api.h
Function Documentation
- int DP_DeepPotGetNumbTypes(DP_DeepPot *dp)
Get the number of types of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The number of types of the DP.
Function DP_DeepPotGetNumbTypesSpin
Defined in File c_api.h
Function Documentation
- int DP_DeepPotGetNumbTypesSpin(DP_DeepPot *dp)
Get the number of types with spin of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The number of types with spin of the DP.
Function DP_DeepPotGetTypeMap
Defined in File c_api.h
Function Documentation
- const char *DP_DeepPotGetTypeMap(DP_DeepPot *dp)
Get the type map of a DP.
- Parameters
dp – [in] The DP to use.
- Returns
The type map of the DP.
Function DP_DeepPotIsAParamNAll
Defined in File c_api.h
Function Documentation
- bool DP_DeepPotIsAParamNAll(DP_DeepPot *dp)
Check whether the atomic dimension of atomic parameters is nall instead of nloc.
- Parameters
dp – [in] The DP to use.
- Returns
true the atomic dimension of atomic parameters is nall
- Returns
false the atomic dimension of atomic parameters is nloc
Function DP_DeepPotModelDeviCheckOK
Defined in File c_api.h
Function Documentation
- const char *DP_DeepPotModelDeviCheckOK(DP_DeepPotModelDevi *dp)
Check if there is any exceptions throw.
- Parameters
dp – The DP model deviation to use.
- Returns
const char* error message.
Function DP_DeepPotModelDeviCompute
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviCompute(DP_DeepPotModelDevi *dp, const int natom, const double *coord, const int *atype, const double *cell, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviCompute2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviCompute2(DP_DeepPotModelDevi *dp, const int nframes, const int natoms, const double *coord, const int *atype, const double *cell, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (double version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
nframes – [in] The number of frames. Only support 1 for now.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x natoms x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputef
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputef(DP_DeepPotModelDevi *dp, const int natom, const float *coord, const int *atype, const float *cell, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputef2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputef2(DP_DeepPotModelDevi *dp, const int nframes, const int natoms, const float *coord, const int *atype, const float *cell, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (float version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
nframes – [in] The number of frames. Only support 1 for now.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x natoms x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputeNList
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputeNList(DP_DeepPotModelDevi *dp, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputeNList2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputeNList2(DP_DeepPotModelDevi *dp, const int nframes, const int natoms, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, const int ago, const double *fparam, const double *aparam, double *energy, double *force, double *virial, double *atomic_energy, double *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (double version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
nframes – [in] The number of frames. Only support 1 for now.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x natoms x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputeNListf
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputeNListf(DP_DeepPotModelDevi *dp, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviComputeNListf2
Defined in File c_api.h
Function Documentation
- void DP_DeepPotModelDeviComputeNListf2(DP_DeepPotModelDevi *dp, const int nframes, const int natoms, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, const int ago, const float *fparam, const float *aparam, double *energy, float *force, float *virial, float *atomic_energy, float *atomic_virial)
Evaluate the energy, force and virial by using a DP model deviation with neighbor list. (float version)
- Version
2
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dp – [in] The DP model deviation to use.
nframes – [in] The number of frames. Only support 1 for now.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
ago – [in] Update the internal neighbour list if ago is 0.
fparam – [in] The frame parameters. The array can be of size nframes x dim_fparam.
aparam – [in] The atom parameters. The array can be of size nframes x natoms x dim_aparam.
energy – [out] Output energy.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_energy – [out] Output atomic energy. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
Function DP_DeepPotModelDeviGetCutoff
Defined in File c_api.h
Function Documentation
- double DP_DeepPotModelDeviGetCutoff(DP_DeepPotModelDevi *dp)
Get the type map of a DP model deviation.
- Parameters
dp – [in] The DP model deviation to use.
- Returns
The cutoff radius.
Function DP_DeepPotModelDeviGetDimAParam
Defined in File c_api.h
Function Documentation
- int DP_DeepPotModelDeviGetDimAParam(DP_DeepPotModelDevi *dp)
Get the dimension of atomic parameters of a DP Model Deviation.
- Parameters
dp – [in] The DP Model Deviation to use.
- Returns
The dimension of atomic parameters of the DP Model Deviation.
Function DP_DeepPotModelDeviGetDimFParam
Defined in File c_api.h
Function Documentation
- int DP_DeepPotModelDeviGetDimFParam(DP_DeepPotModelDevi *dp)
Get the dimension of frame parameters of a DP Model Deviation.
- Parameters
dp – [in] The DP Model Deviation to use.
- Returns
The dimension of frame parameters of the DP Model Deviation.
Function DP_DeepPotModelDeviGetNumbTypes
Defined in File c_api.h
Function Documentation
- int DP_DeepPotModelDeviGetNumbTypes(DP_DeepPotModelDevi *dp)
Get the number of types of a DP model deviation.
- Parameters
dp – [in] The DP model deviation to use.
- Returns
The number of types of the DP model deviation.
Function DP_DeepPotModelDeviGetNumbTypesSpin
Defined in File c_api.h
Function Documentation
- int DP_DeepPotModelDeviGetNumbTypesSpin(DP_DeepPotModelDevi *dp)
Get the number of types with spin of a DP model deviation.
- Parameters
dp – [in] The DP model deviation to use.
- Returns
The number of types with spin of the DP model deviation.
Function DP_DeepPotModelDeviIsAParamNAll
Defined in File c_api.h
Function Documentation
- bool DP_DeepPotModelDeviIsAParamNAll(DP_DeepPotModelDevi *dp)
Check whether the atomic dimension of atomic parameters is nall instead of nloc.
- Parameters
dp – [in] The DP Model Deviation to use.
- Returns
true the atomic dimension of atomic parameters is nall
- Returns
false the atomic dimension of atomic parameters is nloc
Function DP_DeepTensorCheckOK
Defined in File c_api.h
Function Documentation
- const char *DP_DeepTensorCheckOK(DP_DeepTensor *dt)
Check if there is any exceptions throw.
- Parameters
dt – The Deep Tensor to use.
- Returns
const char* error message.
Function DP_DeepTensorCompute
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorCompute(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, double *global_tensor, double *force, double *virial, double **atomic_tensor, double *atomic_virial, int *size_at)
Evaluate the global tensor, force and virial by using a DP. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
global_tensor – [out] Output global tensor.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_tensor – [out] Output atomic tensor. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
size_at – [out] Output size of atomic tensor.
Function DP_DeepTensorComputef
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputef(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, float *global_tensor, float *force, float *virial, float **atomic_tensor, float *atomic_virial, int *size_at)
Evaluate the global tensor, force and virial by using a DP. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
global_tensor – [out] Output global tensor.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_tensor – [out] Output atomic tensor. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
size_at – [out] Output size of atomic tensor.
Function DP_DeepTensorComputeNList
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeNList(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, double *global_tensor, double *force, double *virial, double **atomic_tensor, double *atomic_virial, int *size_at)
Evaluate the global tensor, force and virial by using a DP with the neighbor list. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
global_tensor – [out] Output global tensor.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_tensor – [out] Output atomic tensor. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
size_at – [out] Output size of atomic tensor.
Function DP_DeepTensorComputeNListf
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeNListf(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, float *global_tensor, float *force, float *virial, float **atomic_tensor, float *atomic_virial, int *size_at)
Evaluate the global tensor, force and virial by using a DP with the neighbor list. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
global_tensor – [out] Output global tensor.
force – [out] Output force. The array should be of size natoms x 3.
virial – [out] Output virial. The array should be of size 9.
atomic_tensor – [out] Output atomic tensor. The array should be of size natoms.
atomic_virial – [out] Output atomic virial. The array should be of size natoms x 9.
size_at – [out] Output size of atomic tensor.
Function DP_DeepTensorComputeTensor
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeTensor(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, double **tensor, int *size)
Evaluate the tensor by using a DP. (double version)
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
tensor – [out] Output tensor.
Function DP_DeepTensorComputeTensorf
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeTensorf(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, float **tensor, int *size)
Evaluate the tensor by using a DP. (float version)
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
tensor – [out] Output tensor.
size – [out] Output size of the tensor.
Function DP_DeepTensorComputeTensorNList
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeTensorNList(DP_DeepTensor *dt, const int natom, const double *coord, const int *atype, const double *cell, const int nghost, const DP_Nlist *nlist, double **tensor, int *size)
Evaluate the tensor by using a DP with the neighbor list. (double version)
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
tensor – [out] Output tensor.
size – [out] Output size of the tensor.
Function DP_DeepTensorComputeTensorNListf
Defined in File c_api.h
Function Documentation
- void DP_DeepTensorComputeTensorNListf(DP_DeepTensor *dt, const int natom, const float *coord, const int *atype, const float *cell, const int nghost, const DP_Nlist *nlist, float **tensor, int *size)
Evaluate the tensor by using a DP with the neighbor list. (float version)
- Parameters
dt – [in] The Deep Tensor to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
box – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
tensor – [out] Output tensor.
size – [out] Output size of the tensor.
Function DP_DeepTensorGetCutoff
Defined in File c_api.h
Function Documentation
- double DP_DeepTensorGetCutoff(DP_DeepTensor *dt)
Get the type map of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The cutoff radius.
Function DP_DeepTensorGetNumbSelTypes
Defined in File c_api.h
Function Documentation
- int DP_DeepTensorGetNumbSelTypes(DP_DeepTensor *dt)
Get the number of sel types of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The number of sel types
Function DP_DeepTensorGetNumbTypes
Defined in File c_api.h
Function Documentation
- int DP_DeepTensorGetNumbTypes(DP_DeepTensor *dt)
Get the type map of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The number of types of the Deep Tensor.
Function DP_DeepTensorGetOutputDim
Defined in File c_api.h
Function Documentation
- int DP_DeepTensorGetOutputDim(DP_DeepTensor *dt)
Get the output dimension of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The output dimension of the Deep Tensor.
Function DP_DeepTensorGetSelTypes
Defined in File c_api.h
Function Documentation
- int *DP_DeepTensorGetSelTypes(DP_DeepTensor *dt)
Get sel types of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The sel types
Function DP_DeepTensorGetTypeMap
Defined in File c_api.h
Function Documentation
- const char *DP_DeepTensorGetTypeMap(DP_DeepTensor *dt)
Get the type map of a Deep Tensor.
- Parameters
dt – [in] The Deep Tensor to use.
- Returns
The type map of the Deep Tensor.
Function DP_DeleteChar
Defined in File c_api.h
Function Documentation
- void DP_DeleteChar(const char *c_str)
Destroy a char array.
- Parameters
c_str – The char array.
Function DP_DeleteDeepPot
Defined in File c_api.h
Function Documentation
- void DP_DeleteDeepPot(DP_DeepPot *dp)
Delete a Deep Potential.
- Parameters
dp – Deep Potential to delete.
Function DP_DeleteDeepPotModelDevi
Defined in File c_api.h
Function Documentation
- void DP_DeleteDeepPotModelDevi(DP_DeepPotModelDevi *dp)
Delete a Deep Potential Model Deviation.
- Parameters
dp – Deep Potential to delete.
Function DP_DeleteDeepTensor
Defined in File c_api.h
Function Documentation
- void DP_DeleteDeepTensor(DP_DeepTensor *dt)
Delete a Deep Tensor.
- Parameters
dp – Deep Tensor to delete.
Function DP_DeleteDipoleChargeModifier
Defined in File c_api.h
Function Documentation
- void DP_DeleteDipoleChargeModifier(DP_DipoleChargeModifier *dcm)
Delete a Dipole Charge Modifier.
- Parameters
dp – Dipole Charge Modifier to delete.
Function DP_DeleteNlist
Defined in File c_api.h
Function Documentation
Function DP_DipoleChargeModifierCheckOK
Defined in File c_api.h
Function Documentation
- const char *DP_DipoleChargeModifierCheckOK(DP_DipoleChargeModifier *dcm)
Check if there is any exceptions throw.
- Parameters
dcm – The DipoleChargeModifier to use.
- Returns
const char* error message.
Function DP_DipoleChargeModifierComputeNList
Defined in File c_api.h
Function Documentation
- void DP_DipoleChargeModifierComputeNList(DP_DipoleChargeModifier *dcm, const int natom, const double *coord, const int *atype, const double *cell, const int *pairs, const int npairs, const double *delef_, const int nghost, const DP_Nlist *nlist, double *dfcorr_, double *dvcorr_)
Evaluate the force and virial correction by using a dipole charge modifier with the neighbor list. (double version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dcm – [in] The dipole charge modifier to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size nall x 3.
atype – [in] The atom types. The array should contain nall ints.
cell – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
npairs – [in] The number of pairs.
delef_ – [in] The electric field on each atom. The array should be of size nframes x nloc x 3.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
dfcorr_ – [out] Output force correction. The array should be of size nall x 3.
dvcorr_ – [out] Output virial correction. The array should be of size 9.
Function DP_DipoleChargeModifierComputeNListf
Defined in File c_api.h
Function Documentation
- void DP_DipoleChargeModifierComputeNListf(DP_DipoleChargeModifier *dcm, const int natom, const float *coord, const int *atype, const float *cell, const int *pairs, const int npairs, const float *delef_, const int nghost, const DP_Nlist *nlist, float *dfcorr_, float *dvcorr_)
Evaluate the force and virial correction by using a dipole charge modifier with the neighbor list. (float version)
Warning
The output arrays should be allocated before calling this function. Pass NULL if not required.
- Parameters
dcm – [in] The dipole charge modifier to use.
natoms – [in] The number of atoms.
coord – [in] The coordinates of atoms. The array should be of size natoms x 3.
atype – [in] The atom types. The array should contain natoms ints.
cell – [in] The cell of the region. The array should be of size 9. Pass NULL if pbc is not used.
pairs – [in] The pairs of atoms. The list should contain npairs pairs of ints.
npairs – [in] The number of pairs.
delef_ – [in] The electric field on each atom. The array should be of size nframes x natoms x 3.
nghost – [in] The number of ghost atoms.
nlist – [in] The neighbor list.
dfcorr_ – [out] Output force correction. The array should be of size natoms x 3.
dvcorr_ – [out] Output virial correction. The array should be of size 9.
Function DP_DipoleChargeModifierGetCutoff
Defined in File c_api.h
Function Documentation
- double DP_DipoleChargeModifierGetCutoff(DP_DipoleChargeModifier *dt)
Get the type map of a DipoleChargeModifier.
- Parameters
dcm – [in] The DipoleChargeModifier to use.
- Returns
The cutoff radius.
Function DP_DipoleChargeModifierGetNumbSelTypes
Defined in File c_api.h
Function Documentation
- int DP_DipoleChargeModifierGetNumbSelTypes(DP_DipoleChargeModifier *dt)
Get the number of sel types of a DipoleChargeModifier.
- Parameters
dcm – [in] The DipoleChargeModifier to use.
- Returns
The number of sel types
Function DP_DipoleChargeModifierGetNumbTypes
Defined in File c_api.h
Function Documentation
- int DP_DipoleChargeModifierGetNumbTypes(DP_DipoleChargeModifier *dt)
Get the type map of a DipoleChargeModifier.
- Parameters
dcm – [in] The DipoleChargeModifier to use.
- Returns
The number of types of the DipoleChargeModifier.
Function DP_DipoleChargeModifierGetSelTypes
Defined in File c_api.h
Function Documentation
- int *DP_DipoleChargeModifierGetSelTypes(DP_DipoleChargeModifier *dt)
Get sel types of a DipoleChargeModifier.
- Parameters
dcm – [in] The DipoleChargeModifier to use.
- Returns
The sel types
Function DP_NewDeepPot
Defined in File c_api.h
Function Documentation
- DP_DeepPot *DP_NewDeepPot(const char *c_model)
DP constructor with initialization.
- Parameters
c_model – [in] The name of the frozen model file.
- Returns
A pointer to the deep potential.
Function DP_NewDeepPotModelDevi
Defined in File c_api.h
Function Documentation
- DP_DeepPotModelDevi *DP_NewDeepPotModelDevi(const char **c_models, int n_models)
DP model deviation constructor with initialization.
- Parameters
c_models – [in] The array of the name of the frozen model file.
nmodels – [in] The number of models.
Function DP_NewDeepPotModelDeviWithParam
Defined in File c_api.h
Function Documentation
- DP_DeepPotModelDevi *DP_NewDeepPotModelDeviWithParam(const char **c_model, const int n_models, const int gpu_rank, const char **c_file_contents, const int n_file_contents, const int *size_file_contents)
DP model deviation constructor with initialization.
- Parameters
c_models – [in] The array of the name of the frozen model file.
nmodels – [in] The number of models.
gpu_rank – [in] The rank of the GPU.
c_file_contents – [in] The contents of the model file.
n_file_contents – [in] The number of the contents of the model file.
size_file_contents – [in] The sizes of the contents of the model file.
- Returns
DP_DeepPotModelDevi* A pointer to the deep potential model deviation.
Function DP_NewDeepPotWithParam
Defined in File c_api.h
Function Documentation
- DP_DeepPot *DP_NewDeepPotWithParam(const char *c_model, const int gpu_rank, const char *c_file_content)
DP constructor with initialization.
- Parameters
c_model – The name of the frozen model file.
gpu_rank – The rank of the GPU.
c_file_content – Broken implementation. Use DP_NewDeepPotWithParam2 instead.
- Returns
DP_DeepPot* A pointer to the deep potential.
Function DP_NewDeepPotWithParam2
Defined in File c_api.h
Function Documentation
- DP_DeepPot *DP_NewDeepPotWithParam2(const char *c_model, const int gpu_rank, const char *c_file_content, const int size_file_content)
DP constructor with initialization.
- Version
2
- Parameters
c_model – The name of the frozen model file.
gpu_rank – The rank of the GPU.
c_file_content – The content of the model file.
size_file_content – The size of the model file.
- Returns
DP_DeepPot* A pointer to the deep potential.
Function DP_NewDeepTensor
Defined in File c_api.h
Function Documentation
- DP_DeepTensor *DP_NewDeepTensor(const char *c_model)
Deep Tensor constructor with initialization.
- Parameters
c_model – [in] The name of the frozen model file.
- Returns
A pointer to the deep tensor.
Function DP_NewDeepTensorWithParam
Defined in File c_api.h
Function Documentation
- DP_DeepTensor *DP_NewDeepTensorWithParam(const char *c_model, const int gpu_rank, const char *c_name_scope)
Deep Tensor constructor with initialization.
- Parameters
c_model – The name of the frozen model file.
gpu_rank – The rank of the GPU.
c_name_scope – The name scope.
- Returns
DP_DeepTensor* A pointer to the deep tensor.
Function DP_NewDipoleChargeModifier
Defined in File c_api.h
Function Documentation
- DP_DipoleChargeModifier *DP_NewDipoleChargeModifier(const char *c_model)
Dipole charge modifier constructor with initialization.
- Parameters
c_model – [in] The name of the frozen model file.
- Returns
A pointer to the dipole charge modifier.
Function DP_NewDipoleChargeModifierWithParam
Defined in File c_api.h
Function Documentation
- DP_DipoleChargeModifier *DP_NewDipoleChargeModifierWithParam(const char *c_model, const int gpu_rank, const char *c_name_scope)
Dipole charge modifier constructor with initialization.
- Parameters
c_model – The name of the frozen model file.
gpu_rank – The rank of the GPU.
c_name_scope – The name scope.
- Returns
DP_DipoleChargeModifier* A pointer to the dipole charge modifier.
Function DP_NewNlist
Defined in File c_api.h
Function Documentation
- DP_Nlist *DP_NewNlist(int inum_, int *ilist_, int *numneigh_, int **firstneigh_)
Create a new neighbor list.
- Parameters
inum_ – [in] Number of core region atoms
Array – [in] stores the core region atom’s index
Array – [in] stores the core region atom’s neighbor atom number
Array – [in] stores the core region atom’s neighbor index
- Returns
A pointer to the neighbor list.
Function DP_NlistCheckOK
Defined in File c_api.h
Function Documentation
Function DP_PrintSummary
Defined in File c_api.h
Function Documentation
- void DP_PrintSummary(const char *c_pre)
Print the summary of DeePMD-kit, including the version and the build information.
- Parameters
c_pre – [in] The prefix to each line.
Function DP_ReadFileToChar
Defined in File c_api.h
Function Documentation
- const char *DP_ReadFileToChar(const char *c_model)
Read a file to a char array.
- Parameters
c_model – [in] The name of the file.
- Returns
const char* The char array.
Function DP_ReadFileToChar2
Defined in File c_api.h
Function Documentation
- const char *DP_ReadFileToChar2(const char *c_model, int *size)
Read a file to a char array. This version can handle string with ‘\0’.
- Version
2
- Parameters
c_model – [in] The name of the file.
size – [out] The size of the char array.
- Returns
const char* The char array.
Function DP_SelectByType
Defined in File c_api.h
Function Documentation
- void DP_SelectByType(const int natoms, const int *atype, const int nghost, const int nsel_type, const int *sel_type, int *fwd_map, int *nreal, int *bkw_map, int *nghost_real)
Get forward and backward map of selected atoms by atom types.
- Parameters
natoms – [in] The number of atoms.
atype – [in] The atom types of all atoms.
nghost – [in] The number of ghost atoms.
nsel_type – [in] The number of selected atom types.
sel_type – [in] The selected atom types.
fwd_map – [out] The forward map with size natoms.
nreal – [out] The number of selected real atoms.
bkw_map – [out] The backward map with size nreal.
nghost_real – [out] The number of selected ghost atoms.
Function DP_SelectMapInt
Defined in File c_api.h
Function Documentation
- void DP_SelectMapInt(const int *in, const int *fwd_map, const int stride, const int nall1, const int nall2, int *out)
Apply the given map to a vector. Assume nframes is 1.
- Parameters
in – [in] The input vector.
fwd_map – [in] The map.
stride – [in] The stride of the input vector.
nall1 – [in] The number of atoms in the input vector.
nall2 – [out] The number of atoms in the output vector.
out – [out] The output vector.
Defines
Define DP_CHECK_OK
Defined in File deepmd.hpp
Define Documentation
- DP_CHECK_OK(check_func, dp)
Check if any exceptions throw in the C++ API. Throw if possible.
Define DP_NEW_OK
Defined in File c_api_internal.h
Define Documentation
- DP_NEW_OK(dpcls, xx)
Define DP_REQUIRES_OK
Defined in File c_api_internal.h
Define Documentation
- DP_REQUIRES_OK(dp, xx)
Typedefs
Typedef DP_DeepPot
Defined in File c_api.h
Typedef Documentation
- typedef struct DP_DeepPot DP_DeepPot
The deep potential.
Typedef DP_DeepPotModelDevi
Defined in File c_api.h
Typedef Documentation
- typedef struct DP_DeepPotModelDevi DP_DeepPotModelDevi
The deep potential model deviation.
Typedef DP_DeepTensor
Defined in File c_api.h
Typedef Documentation
- typedef struct DP_DeepTensor DP_DeepTensor
The deep tensor.
Typedef DP_DipoleChargeModifier
Defined in File c_api.h
Typedef Documentation
- typedef struct DP_DipoleChargeModifier DP_DipoleChargeModifier
The dipole charge modifier.
Typedef DP_Nlist
Defined in File c_api.h
Typedef Documentation
- typedef struct DP_Nlist DP_Nlist
Neighbor list.
Core API
Class Hierarchy
File Hierarchy
Full API
Namespaces
Namespace deepmd
Classes
Functions
Function deepmd::cos_switch(const double&, const double&, const double&)
Function deepmd::cos_switch(double&, double&, const double&, const double&, const double&)
Template Function deepmd::malloc_device_memory(FPTYPE *&, const std::vector<FPTYPE>&)
Template Function deepmd::malloc_device_memory(FPTYPE *&, const int)
Template Function deepmd::malloc_device_memory(FPTYPE *&, std::vector<FPTYPE>&)
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, const std::vector<FPTYPE>&)
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, const FPTYPE *, const int)
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, std::vector<FPTYPE>&)
Template Function deepmd::memcpy_device_to_host(const FPTYPE *, std::vector<FPTYPE>&)
Template Function deepmd::memcpy_device_to_host(const FPTYPE *, FPTYPE *, const int)
Template Function deepmd::memcpy_host_to_device(FPTYPE *, std::vector<FPTYPE>&)
Template Function deepmd::memcpy_host_to_device(FPTYPE *, const FPTYPE *, const int)
Template Function deepmd::memcpy_host_to_device(FPTYPE *, const std::vector<FPTYPE>&)
Template Function deepmd::tabulate_fusion_se_a_grad_grad_cpu
Template Function deepmd::tabulate_fusion_se_a_grad_grad_gpu
Template Function deepmd::tabulate_fusion_se_r_grad_grad_cpu
Template Function deepmd::tabulate_fusion_se_r_grad_grad_gpu
Template Function deepmd::tabulate_fusion_se_t_grad_grad_cpu
Template Function deepmd::tabulate_fusion_se_t_grad_grad_gpu
Template Function deepmd::test_encoding_decoding_nbor_info_gpu
Variables
Namespace std
Classes and Structs
Struct deepmd_exception
Defined in File errors.h
Inheritance Relationships
public std::runtime_error
public deepmd::deepmd_exception_oom(Struct deepmd_exception_oom)
Struct Documentation
- struct deepmd_exception : public std::runtime_error
General DeePMD-kit exception. Throw if anything doesn’t work.
Subclassed by deepmd::deepmd_exception_oom
Struct deepmd_exception_oom
Defined in File errors.h
Inheritance Relationships
public deepmd::deepmd_exception(Struct deepmd_exception)
Struct Documentation
- struct deepmd_exception_oom : public deepmd::deepmd_exception
Template Struct EwaldParameters
Defined in File ewald.h
Struct Documentation
- template<typename VALUETYPE>
struct EwaldParameters
Struct InputNlist
Defined in File neighbor_list.h
Struct Documentation
- struct InputNlist
Construct InputNlist with the input LAMMPS nbor list info.
Template Struct Region
Defined in File region.h
Struct Documentation
- template<typename FPTYPE>
struct Region
Template Struct DescrptSeRGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct DescrptSeRGPUExecuteFunctor Public Functions
- void operator()(const FPTYPE *coord, const int *type, const int *ilist, const int *jrange, const int *jlist, int *array_int, unsigned long long *array_longlong, const FPTYPE *avg, const FPTYPE *std, FPTYPE *descript, FPTYPE *descript_deriv, FPTYPE *rij, int *nlist, const int nloc, const int nall, const int nnei, const int ndescrpt, const float rcut_r, const float rcut_r_smth, const std::vector<int> sec_a, const bool fill_nei_a, const int MAGIC_NUMBER)
- void operator()(const FPTYPE *coord, const int *type, const int *ilist, const int *jrange, const int *jlist, int *array_int, unsigned long long *array_longlong, const FPTYPE *avg, const FPTYPE *std, FPTYPE *descript, FPTYPE *descript_deriv, FPTYPE *rij, int *nlist, const int nloc, const int nall, const int nnei, const int ndescrpt, const float rcut_r, const float rcut_r_smth, const std::vector<int> sec_a, const bool fill_nei_a, const int MAGIC_NUMBER)
Template Struct GeluGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct GeluGPUExecuteFunctor
Template Struct GeluGradGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct GeluGradGPUExecuteFunctor
Template Struct GeluGradGradGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct GeluGradGradGPUExecuteFunctor
Template Struct ProdForceSeAGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct ProdForceSeAGPUExecuteFunctor
Template Struct ProdForceSeRGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct ProdForceSeRGPUExecuteFunctor
Template Struct ProdVirialSeAGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct ProdVirialSeAGPUExecuteFunctor
Template Struct ProdVirialSeRGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct ProdVirialSeRGPUExecuteFunctor
Template Struct TabulateCheckerGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct TabulateCheckerGPUExecuteFunctor
Template Struct TabulateFusionGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct TabulateFusionGPUExecuteFunctor
Template Struct TabulateFusionGradGPUExecuteFunctor
Defined in File DeviceFunctor.h
Struct Documentation
- template<typename FPTYPE>
struct TabulateFusionGradGPUExecuteFunctor
Template Class SimulationRegion
Defined in File SimulationRegion.h
Class Documentation
- template<typename VALUETYPE>
class SimulationRegion Public Functions
- inline void reinitBox(const double *boxv)
- inline void affineTransform(const double *affine_map)
- inline void reinitOrigin(const double *orig)
- inline void reinitOrigin(const std::vector<double> &orig)
- void backup()
- void recover()
- SimulationRegion()
- ~SimulationRegion()
- inline double *getBoxTensor()
- inline const double *getBoxTensor() const
- inline double *getRecBoxTensor()
- inline const double *getRecBoxTensor() const
- inline double *getBoxOrigin()
- inline const double *getBoxOrigin() const
- inline double getVolume() const
- inline void toFaceDistance(double *dd) const
- inline bool isPeriodic(const int dim) const
- inline double *getShiftVec(const int index = 0)
- inline const double *getShiftVec(const int index = 0) const
- inline int getShiftIndex(const int *idx) const
- inline int getNullShiftIndex() const
- inline virtual void diffNearestNeighbor(const VALUETYPE x0, const VALUETYPE y0, const VALUETYPE z0, const VALUETYPE x1, const VALUETYPE y1, const VALUETYPE z1, VALUETYPE &dx, VALUETYPE &dy, VALUETYPE &dz) const
Public Static Functions
- static inline int compactIndex(const int *idx)
- static inline int getNumbShiftVec()
- static inline int getShiftVecTotalSize()
Protected Functions
- void computeShiftVec()
- inline double *getInterShiftVec(const int index = 0)
- inline const double *getInterShiftVec(const int index = 0) const
Protected Static Functions
- static inline int index3to1(const int tx, const int ty, const int tz)
- inline void reinitBox(const double *boxv)
Unions
Functions
Template Function add_flt_nvnmd
Defined in File env_mat_nvnmd.h
Function Documentation
Function build_nlist(std::vector<std::vector<int>>&, std::vector<std::vector<int>>&, const std::vector<double>&, const int&, const double&, const double&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const SimulationRegion<double>&, const std::vector<int>&)
Defined in File neighbor_list.h
Function Documentation
- void build_nlist(std::vector<std::vector<int>> &nlist0, std::vector<std::vector<int>> &nlist1, const std::vector<double> &coord, const int &nloc, const double &rc0, const double &rc1, const std::vector<int> &nat_stt_, const std::vector<int> &nat_end_, const std::vector<int> &ext_stt_, const std::vector<int> &ext_end_, const SimulationRegion<double> ®ion, const std::vector<int> &global_grid)
Function build_nlist(std::vector<std::vector<int>>&, std::vector<std::vector<int>>&, const std::vector<double>&, const double&, const double&, const std::vector<int>&, const SimulationRegion<double>&)
Defined in File neighbor_list.h
Function Documentation
- void build_nlist(std::vector<std::vector<int>> &nlist0, std::vector<std::vector<int>> &nlist1, const std::vector<double> &coord, const double &rc0, const double &rc1, const std::vector<int> &grid, const SimulationRegion<double> ®ion)
Function build_nlist(std::vector<std::vector<int>>&, std::vector<std::vector<int>>&, const std::vector<double>&, const std::vector<int>&, const std::vector<int>&, const double&, const double&, const std::vector<int>&, const SimulationRegion<double>&)
Defined in File neighbor_list.h
Function Documentation
- void build_nlist(std::vector<std::vector<int>> &nlist0, std::vector<std::vector<int>> &nlist1, const std::vector<double> &coord, const std::vector<int> &sel0, const std::vector<int> &sel1, const double &rc0, const double &rc1, const std::vector<int> &grid, const SimulationRegion<double> ®ion)
Function build_nlist(std::vector<std::vector<int>>&, std::vector<std::vector<int>>&, const std::vector<double>&, const double&, const double&, const SimulationRegion<double> *)
Defined in File neighbor_list.h
Function Documentation
- void build_nlist(std::vector<std::vector<int>> &nlist0, std::vector<std::vector<int>> &nlist1, const std::vector<double> &coord, const double &rc0_, const double &rc1_, const SimulationRegion<double> *region = NULL)
Function compute_descriptor(std::vector<double>&, std::vector<double>&, std::vector<double>&, const std::vector<double>&, const int&, const std::vector<int>&, const SimulationRegion<double>&, const bool&, const int&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const int, const int, const int, const int)
Defined in File ComputeDescriptor.h
Function Documentation
- inline void compute_descriptor(std::vector<double> &descrpt_a, std::vector<double> &descrpt_r, std::vector<double> &rot_mat, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &fmt_nlist_r, const std::vector<int> &sec_a, const std::vector<int> &sec_r, const int axis0_type, const int axis0_idx, const int axis1_type, const int axis1_idx)
Function compute_descriptor(std::vector<double>&, std::vector<double>&, std::vector<double>&, std::vector<double>&, std::vector<double>&, std::vector<double>&, std::vector<double>&, const std::vector<double>&, const int&, const std::vector<int>&, const SimulationRegion<double>&, const bool&, const int&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const std::vector<int>&, const int, const int, const int, const int)
Defined in File ComputeDescriptor.h
Function Documentation
- inline void compute_descriptor(std::vector<double> &descrpt_a, std::vector<double> &descrpt_a_deriv, std::vector<double> &descrpt_r, std::vector<double> &descrpt_r_deriv, std::vector<double> &rij_a, std::vector<double> &rij_r, std::vector<double> &rot_mat, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &fmt_nlist_r, const std::vector<int> &sec_a, const std::vector<int> &sec_r, const int axis0_type, const int axis0_idx, const int axis1_type, const int axis1_idx)
Function compute_descriptor_se_a_ef_para
Defined in File ComputeDescriptor.h
Function Documentation
- inline void compute_descriptor_se_a_ef_para(std::vector<double> &descrpt_a, std::vector<double> &descrpt_a_deriv, std::vector<double> &rij_a, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const std::vector<double> &efield, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &sec_a, const double &rmin, const double &rmax)
Function compute_descriptor_se_a_ef_vert
Defined in File ComputeDescriptor.h
Function Documentation
- inline void compute_descriptor_se_a_ef_vert(std::vector<double> &descrpt_a, std::vector<double> &descrpt_a_deriv, std::vector<double> &rij_a, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const std::vector<double> &efield, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &sec_a, const double &rmin, const double &rmax)
Function compute_descriptor_se_a_extf
Defined in File ComputeDescriptor.h
Function Documentation
- inline void compute_descriptor_se_a_extf(std::vector<double> &descrpt_a, std::vector<double> &descrpt_a_deriv, std::vector<double> &rij_a, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const std::vector<double> &efield, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &sec_a, const double &rmin, const double &rmax)
Function compute_dRdT
Defined in File ComputeDescriptor.h
Function Documentation
Warning
doxygenfunction: Unable to resolve function “compute_dRdT” with arguments (double (*), const double*, const double*, const double*) in doxygen xml output for project “core” from directory: _build/core/xml/. Potential matches:
- void compute_dRdT(double (*dRdT)[9], const double *r1, const double *r2, const double *rot)
Function compute_dRdT_1
Defined in File ComputeDescriptor.h
Function Documentation
Warning
doxygenfunction: Unable to resolve function “compute_dRdT_1” with arguments (double (*), const double*, const double*, const double*) in doxygen xml output for project “core” from directory: _build/core/xml/. Potential matches:
- void compute_dRdT_1(double (*dRdT)[9], const double *r1, const double *r2, const double *rot)
Function compute_dRdT_2
Defined in File ComputeDescriptor.h
Function Documentation
Warning
doxygenfunction: Unable to resolve function “compute_dRdT_2” with arguments (double (*), const double*, const double*, const double*) in doxygen xml output for project “core” from directory: _build/core/xml/. Potential matches:
- void compute_dRdT_2(double (*dRdT)[9], const double *r1, const double *r2, const double *rot)
Function copy_coord
Defined in File neighbor_list.h
Function Documentation
- void copy_coord(std::vector<double> &out_c, std::vector<int> &out_t, std::vector<int> &mapping, std::vector<int> &ncell, std::vector<int> &ngcell, const std::vector<double> &in_c, const std::vector<int> &in_t, const double &rc, const SimulationRegion<double> ®ion)
Template Function deepmd::build_nlist_cpu
Defined in File neighbor_list.h
Function Documentation
- template<typename FPTYPE>
int deepmd::build_nlist_cpu(InputNlist &nlist, int *max_list_size, const FPTYPE *c_cpy, const int &nloc, const int &nall, const int &mem_size, const float &rcut)
Template Function deepmd::build_nlist_gpu
Defined in File neighbor_list.h
Function Documentation
- template<typename FPTYPE>
int deepmd::build_nlist_gpu(InputNlist &nlist, int *max_list_size, int *nlist_data, const FPTYPE *c_cpy, const int &nloc, const int &nall, const int &mem_size, const float &rcut)
Template Function deepmd::compute_cell_info
Defined in File coord.h
Function Documentation
Function deepmd::convert_nlist
Defined in File neighbor_list.h
Function Documentation
- void deepmd::convert_nlist(InputNlist &to_nlist, std::vector<std::vector<int>> &from_nlist)
Construct the InputNlist with a two-dimensional vector.
- Parameters
to_nlist – InputNlist struct which stores the neighbor information of the core region atoms.
from_nlist – Vector which stores the neighbor information of the core region atoms.
Function deepmd::convert_nlist_gpu_device
Defined in File neighbor_list.h
Function Documentation
- void deepmd::convert_nlist_gpu_device(InputNlist &gpu_nlist, InputNlist &cpu_nlist, int *&gpu_memory, const int &max_nbor_size)
Convert the a host memory InputNlist to a device memory InputNlist.
- Parameters
cpu_nlist – Host memory InputNlist struct which stores the neighbor information of the core region atoms
gpu_nlist – Device memory InputNlist struct which stores the neighbor information of the core region atoms
gpu_memory – Device array which stores the elements of gpu_nlist
max_nbor_size –
Template Function deepmd::convert_to_inter_cpu
Defined in File region.h
Function Documentation
Template Function deepmd::convert_to_inter_gpu
Defined in File region.h
Function Documentation
Template Function deepmd::convert_to_phys_cpu
Defined in File region.h
Function Documentation
Template Function deepmd::convert_to_phys_gpu
Defined in File region.h
Function Documentation
Template Function deepmd::copy_coord_cpu
Defined in File coord.h
Function Documentation
Template Function deepmd::copy_coord_gpu
Defined in File coord.h
Function Documentation
- template<typename FPTYPE>
int deepmd::copy_coord_gpu(FPTYPE *out_c, int *out_t, int *mapping, int *nall, int *int_data, const FPTYPE *in_c, const int *in_t, const int &nloc, const int &mem_nall, const int &loc_cellnum, const int &total_cellnum, const int *cell_info, const deepmd::Region<FPTYPE> ®ion)
Function deepmd::cos_switch(const double&, const double&, const double&)
Defined in File switcher.h
Function Documentation
- inline double deepmd::cos_switch(const double &xx, const double &rmin, const double &rmax)
Function deepmd::cos_switch(double&, double&, const double&, const double&, const double&)
Defined in File switcher.h
Function Documentation
- inline void deepmd::cos_switch(double &vv, double &dd, const double &xx, const double &rmin, const double &rmax)
Template Function deepmd::cprod
Defined in File utilities.h
Function Documentation
Function deepmd::cum_sum
Defined in File utilities.h
Function Documentation
- void deepmd::cum_sum(std::vector<int> &sec, const std::vector<int> &n_sel)
Template Function deepmd::delete_device_memory
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::dot1
Defined in File utilities.h
Function Documentation
Template Function deepmd::dot2
Defined in File utilities.h
Function Documentation
Template Function deepmd::dot3
Defined in File utilities.h
Function Documentation
Template Function deepmd::dot4
Defined in File utilities.h
Function Documentation
Template Function deepmd::dotmv3
Defined in File utilities.h
Function Documentation
Function deepmd::DPGetDeviceCount
Defined in File gpu_cuda.h
Function Documentation
- inline void deepmd::DPGetDeviceCount(int &gpu_num)
Function deepmd::dprc_pairwise_map_cpu
Defined in File pairwise.h
Function Documentation
- void deepmd::dprc_pairwise_map_cpu(std::vector<int> &forward_qm_map, std::vector<int> &backward_qm_map, std::vector<int> &forward_qmmm_map, std::vector<int> &backward_qmmm_map, int &nloc_qm, int &nloc_qmmm, int &nall_qm, int &nall_qmmm, const std::vector<std::vector<int>> &fragments, const int nloc, const int nall)
DPRc pairwise map.
- Parameters
forward_qm_map – [out] Forward map for QM atoms.
backward_qm_map – [out] Backward map for QM atoms.
forward_qmmm_map – [out] Forward map for QM/MM atoms.
backward_qmmm_map – [out] Backward map for QM/MM atoms.
nloc_qm – [out] The number of local QM atoms.
nloc_qmmm – [out] The number of local QM/MM atoms.
nall_qm – [out] The number of all QM atoms, including local and ghost atoms.
nall_qmmm – [out] The number of all QM/MM atoms, including local and ghost atoms.
fragments – [in] The indexes of atoms that each fragment contains. Assume that only the first fragment consists of QM atoms.
nloc – [in] The number of local atoms.
nall – [in] The number of all atoms, including local and ghost atoms.
Function deepmd::DPSetDevice
Defined in File gpu_cuda.h
Function Documentation
- inline cudaError_t deepmd::DPSetDevice(int rank)
Template Function deepmd::env_mat_a_cpu
Defined in File env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::env_mat_a_cpu(std::vector<FPTYPE> &descrpt_a, std::vector<FPTYPE> &descrpt_a_deriv, std::vector<FPTYPE> &rij_a, const std::vector<FPTYPE> &posi, const std::vector<int> &type, const int &i_idx, const std::vector<int> &fmt_nlist, const std::vector<int> &sec, const float &rmin, const float &rmax)
Template Function deepmd::env_mat_a_nvnmd_quantize_cpu
Defined in File env_mat_nvnmd.h
Function Documentation
- template<typename FPTYPE>
void deepmd::env_mat_a_nvnmd_quantize_cpu(std::vector<FPTYPE> &descrpt_a, std::vector<FPTYPE> &descrpt_a_deriv, std::vector<FPTYPE> &rij_a, const std::vector<FPTYPE> &posi, const std::vector<int> &type, const int &i_idx, const std::vector<int> &fmt_nlist, const std::vector<int> &sec, const float &rmin, const float &rmax)
Function deepmd::env_mat_nbor_update
Defined in File prod_env_mat.h
Function Documentation
- void deepmd::env_mat_nbor_update(InputNlist &inlist, InputNlist &gpu_inlist, int &max_nbor_size, int *&nbor_list_dev, const int *mesh, const int size)
Template Function deepmd::env_mat_r_cpu
Defined in File env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::env_mat_r_cpu(std::vector<FPTYPE> &descrpt_a, std::vector<FPTYPE> &descrpt_a_deriv, std::vector<FPTYPE> &rij_a, const std::vector<FPTYPE> &posi, const std::vector<int> &type, const int &i_idx, const std::vector<int> &fmt_nlist_a, const std::vector<int> &sec_a, const float &rmin, const float &rmax)
Template Function deepmd::ewald_recp
Defined in File ewald.h
Function Documentation
Function deepmd::filter_ftype_gpu
Defined in File neighbor_list.h
Function Documentation
- void deepmd::filter_ftype_gpu(int *ftype_out, const int *ftype_in, const int nloc)
Filter the fake atom type.
If >=0, set to 0; if <0, set to -1.
- Parameters
ftype_out – The output filtered atom type.
ftype_in – The input atom type.
nloc – The number of atoms.
Template Function deepmd::format_nbor_list_gpu
Defined in File fmt_nlist.h
Function Documentation
- template<typename FPTYPE>
void deepmd::format_nbor_list_gpu(int *nlist, const FPTYPE *coord, const int *type, const deepmd::InputNlist &gpu_inlist, int *array_int, uint_64 *array_longlong, const int max_nbor_size, const int nloc, const int nall, const float rcut, const std::vector<int> sec)
Template Function deepmd::format_nlist_cpu
Defined in File fmt_nlist.h
Function Documentation
- template<typename FPTYPE>
void deepmd::format_nlist_cpu(int *nlist, const InputNlist &in_nlist, const FPTYPE *coord, const int *type, const int nloc, const int nall, const float rcut, const std::vector<int> sec)
Function deepmd::free_nlist_gpu_device
Defined in File neighbor_list.h
Function Documentation
- void deepmd::free_nlist_gpu_device(InputNlist &gpu_nlist)
Reclaim the allocated device memory of struct InputNlist.
- Parameters
gpu_nlist – Device memory InputNlist struct which stores the neighbor information of the core region atoms
Template Function deepmd::gelu_cpu
Defined in File gelu.h
Function Documentation
Template Function deepmd::gelu_gpu
Defined in File gelu.h
Function Documentation
Template Function deepmd::gelu_grad_cpu
Defined in File gelu.h
Function Documentation
Template Function deepmd::gelu_grad_gpu
Defined in File gelu.h
Function Documentation
Template Function deepmd::gelu_grad_grad_cpu
Defined in File gelu.h
Function Documentation
Template Function deepmd::gelu_grad_grad_gpu
Defined in File gelu.h
Function Documentation
Function deepmd::group_atoms_cpu
Defined in File pairwise.h
Function Documentation
- void deepmd::group_atoms_cpu(std::vector<std::vector<int>> &fragments, const std::vector<int> &idxs)
Group atoms into different fragments according to indexes.
- Parameters
fragments – [out] The indexes of atoms that each fragment contains. Fragment has been sorted.
idxs – [in] The indexes of the fragment that each atom belongs to. -1 will be ignored.
Template Function deepmd::init_region_cpu
Defined in File region.h
Function Documentation
Template Function deepmd::invsqrt
Defined in File utilities.h
Function Documentation
Specialized Template Function deepmd::invsqrt< double >
Defined in File utilities.h
Function Documentation
- template<>
inline double deepmd::invsqrt<double>(const double x)
Specialized Template Function deepmd::invsqrt< float >
Defined in File utilities.h
Function Documentation
- template<>
inline float deepmd::invsqrt<float>(const float x)
Template Function deepmd::malloc_device_memory(FPTYPE *&, const std::vector<FPTYPE>&)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::malloc_device_memory(FPTYPE *&, const int)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::malloc_device_memory(FPTYPE *&, std::vector<FPTYPE>&)
Defined in File gpu_rocm.h
Function Documentation
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, const std::vector<FPTYPE>&)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, const FPTYPE *, const int)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::malloc_device_memory_sync(FPTYPE *&, std::vector<FPTYPE>&)
Defined in File gpu_rocm.h
Function Documentation
Template Function deepmd::map_aparam_cpu
Defined in File map_aparam.h
Function Documentation
Function deepmd::max_numneigh
Defined in File neighbor_list.h
Function Documentation
- int deepmd::max_numneigh(const InputNlist &to_nlist)
Compute the max number of neighbors within the core region atoms.
- Parameters
to_nlist – InputNlist struct which stores the neighbor information of the core region atoms.
- Return values
max – number of neighbors
- Returns
integer
Template Function deepmd::memcpy_device_to_host(const FPTYPE *, std::vector<FPTYPE>&)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::memcpy_device_to_host(const FPTYPE *, FPTYPE *, const int)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::memcpy_host_to_device(FPTYPE *, const std::vector<FPTYPE>&)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::memcpy_host_to_device(FPTYPE *, const FPTYPE *, const int)
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::memcpy_host_to_device(FPTYPE *, std::vector<FPTYPE>&)
Defined in File gpu_rocm.h
Function Documentation
Template Function deepmd::memset_device_memory
Defined in File gpu_cuda.h
Function Documentation
Template Function deepmd::neighbor_stat_gpu
Defined in File neighbor_stat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::neighbor_stat_gpu(const FPTYPE *coord, const int *type, const int nloc, const deepmd::InputNlist &gpu_nlist, int *max_nbor_size, FPTYPE *min_nbor_dist, const int ntypes, const int MAX_NNEI)
Template Function deepmd::normalize_coord_cpu
Defined in File coord.h
Function Documentation
Template Function deepmd::normalize_coord_gpu
Defined in File coord.h
Function Documentation
Template Function deepmd::pair_tab_cpu
Defined in File pair_tab.h
Function Documentation
- template<typename FPTYPE>
void deepmd::pair_tab_cpu(FPTYPE *energy, FPTYPE *force, FPTYPE *virial, const double *table_info, const double *table_data, const FPTYPE *rij, const FPTYPE *scale, const int *type, const int *nlist, const int *natoms, const std::vector<int> &sel_a, const std::vector<int> &sel_r)
Template Function deepmd::prod_env_mat_a_cpu
Defined in File prod_env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_env_mat_a_cpu(FPTYPE *em, FPTYPE *em_deriv, FPTYPE *rij, int *nlist, const FPTYPE *coord, const int *type, const InputNlist &inlist, const int max_nbor_size, const FPTYPE *avg, const FPTYPE *std, const int nloc, const int nall, const float rcut, const float rcut_smth, const std::vector<int> sec, const int *f_type = NULL)
Template Function deepmd::prod_env_mat_a_gpu
Defined in File prod_env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_env_mat_a_gpu(FPTYPE *em, FPTYPE *em_deriv, FPTYPE *rij, int *nlist, const FPTYPE *coord, const int *type, const InputNlist &gpu_inlist, int *array_int, unsigned long long *array_longlong, const int max_nbor_size, const FPTYPE *avg, const FPTYPE *std, const int nloc, const int nall, const float rcut, const float rcut_smth, const std::vector<int> sec, const int *f_type = NULL)
Template Function deepmd::prod_env_mat_a_nvnmd_quantize_cpu
Defined in File prod_env_mat_nvnmd.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_env_mat_a_nvnmd_quantize_cpu(FPTYPE *em, FPTYPE *em_deriv, FPTYPE *rij, int *nlist, const FPTYPE *coord, const int *type, const InputNlist &inlist, const int max_nbor_size, const FPTYPE *avg, const FPTYPE *std, const int nloc, const int nall, const float rcut, const float rcut_smth, const std::vector<int> sec, const int *f_type = NULL)
Template Function deepmd::prod_env_mat_r_cpu
Defined in File prod_env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_env_mat_r_cpu(FPTYPE *em, FPTYPE *em_deriv, FPTYPE *rij, int *nlist, const FPTYPE *coord, const int *type, const InputNlist &inlist, const int max_nbor_size, const FPTYPE *avg, const FPTYPE *std, const int nloc, const int nall, const float rcut, const float rcut_smth, const std::vector<int> sec)
Template Function deepmd::prod_env_mat_r_gpu
Defined in File prod_env_mat.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_env_mat_r_gpu(FPTYPE *em, FPTYPE *em_deriv, FPTYPE *rij, int *nlist, const FPTYPE *coord, const int *type, const InputNlist &gpu_inlist, int *array_int, unsigned long long *array_longlong, const int max_nbor_size, const FPTYPE *avg, const FPTYPE *std, const int nloc, const int nall, const float rcut, const float rcut_smth, const std::vector<int> sec)
Template Function deepmd::prod_force_a_cpu(FPTYPE *, const FPTYPE *, const FPTYPE *, const int *, const int, const int, const int, const int)
Defined in File prod_force.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_force_a_cpu(FPTYPE *force, const FPTYPE *net_deriv, const FPTYPE *in_deriv, const int *nlist, const int nloc, const int nall, const int nnei, const int nframes) Produce force from net_deriv and in_deriv.
- Template Parameters
FPTYPE – float or double
- Parameters
force – [out] Atomic forces.
net_deriv – [in] Net derivative.
in_deriv – [in] Environmental derivative.
nlist – [in] Neighbor list.
nloc – [in] The number of local atoms.
nall – [in] The number of all atoms, including ghost atoms.
nnei – [in] The number of neighbors.
nframes – [in] The number of frames.
Template Function deepmd::prod_force_a_cpu(FPTYPE *, const FPTYPE *, const FPTYPE *, const int *, const int, const int, const int, const int, const int, const int)
Defined in File prod_force.h
Function Documentation
- template<typename FPTYPE>
void deepmd::prod_force_a_cpu(FPTYPE *force, const FPTYPE *net_deriv, const FPTYPE *in_deriv, const int *nlist, const int nloc, const int nall, const int nnei, const int nframes, const int thread_nloc, const int thread_start_index) Produce force from net_deriv and in_deriv.
This function is used for multi-threading. Only part of atoms are computed in this thread. They will be comptued in parallel.
- Template Parameters
FPTYPE – float or double
- Parameters
force – [out] Atomic forces.
net_deriv – [in] Net derivative.
in_deriv – [in] Environmental derivative.
nlist – [in] Neighbor list.
nloc – [in] The number of local atoms.
nall – [in] The number of all atoms, including ghost atoms.
nnei – [in] The number of neighbors.
nframes – [in] The number of frames.
thread_nloc – [in] The number of local atoms to be computed in this thread.
thread_start_index – [in] The start index of local atoms to be computed in this thread. The index should be in [0, nloc).
Template Function deepmd::prod_force_a_gpu
Defined in File prod_force.h
Function Documentation
Template Function deepmd::prod_force_grad_a_cpu
Defined in File prod_force_grad.h
Function Documentation
Template Function deepmd::prod_force_grad_a_gpu
Defined in File prod_force_grad.h
Function Documentation
Template Function deepmd::prod_force_grad_r_cpu
Defined in File prod_force_grad.h
Function Documentation
Template Function deepmd::prod_force_grad_r_gpu
Defined in File prod_force_grad.h
Function Documentation
Template Function deepmd::prod_force_r_cpu
Defined in File prod_force.h
Function Documentation
Template Function deepmd::prod_force_r_gpu
Defined in File prod_force.h
Function Documentation
Template Function deepmd::prod_virial_a_cpu
Defined in File prod_virial.h
Function Documentation
Template Function deepmd::prod_virial_a_gpu
Defined in File prod_virial.h
Function Documentation
Template Function deepmd::prod_virial_grad_a_cpu
Defined in File prod_virial_grad.h
Function Documentation
Template Function deepmd::prod_virial_grad_a_gpu
Defined in File prod_virial_grad.h
Function Documentation
Template Function deepmd::prod_virial_grad_r_cpu
Defined in File prod_virial_grad.h
Function Documentation
Template Function deepmd::prod_virial_grad_r_gpu
Defined in File prod_virial_grad.h
Function Documentation
Template Function deepmd::prod_virial_r_cpu
Defined in File prod_virial.h
Function Documentation
Template Function deepmd::prod_virial_r_gpu
Defined in File prod_virial.h
Function Documentation
Template Function deepmd::soft_min_switch_cpu
Defined in File soft_min_switch.h
Function Documentation
Template Function deepmd::soft_min_switch_force_cpu
Defined in File soft_min_switch_force.h
Function Documentation
Template Function deepmd::soft_min_switch_force_grad_cpu
Defined in File soft_min_switch_force_grad.h
Function Documentation
Template Function deepmd::soft_min_switch_virial_cpu
Defined in File soft_min_switch_virial.h
Function Documentation
Template Function deepmd::soft_min_switch_virial_grad_cpu
Defined in File soft_min_switch_virial_grad.h
Function Documentation
Function deepmd::spline3_switch
Defined in File switcher.h
Function Documentation
- inline void deepmd::spline3_switch(double &vv, double &dd, const double &xx, const double &rmin, const double &rmax)
Template Function deepmd::spline5_switch
Defined in File switcher.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_a_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_a_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_a_grad_cpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_a_grad_cpu(FPTYPE *dy_dem_x, FPTYPE *dy_dem, FPTYPE *dy_dtwo, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *two_embed, const FPTYPE *dy, const int nloc, const int nnei, const int last_layer_size, const bool is_sorted = true)
Template Function deepmd::tabulate_fusion_se_a_grad_gpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_a_grad_gpu(FPTYPE *dy_dem_x, FPTYPE *dy_dem, FPTYPE *dy_dtwo, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *two_embed, const FPTYPE *dy, const int nloc, const int nnei, const int last_layer_size, const bool is_sorted = true)
Template Function deepmd::tabulate_fusion_se_a_grad_grad_cpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_a_grad_grad_cpu(FPTYPE *dz_dy, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *two_embed, const FPTYPE *dz_dy_dem_x, const FPTYPE *dz_dy_dem, const FPTYPE *dz_dy_dtwo, const int nloc, const int nnei, const int last_layer_size, const bool is_sorted = true)
Template Function deepmd::tabulate_fusion_se_a_grad_grad_gpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_a_grad_grad_gpu(FPTYPE *dz_dy, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *two_embed, const FPTYPE *dz_dy_dem_x, const FPTYPE *dz_dy_dem, const FPTYPE *dz_dy_dtwo, const int nloc, const int nnei, const int last_layer_size, const bool is_sorted = true)
Template Function deepmd::tabulate_fusion_se_r_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_r_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_r_grad_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_r_grad_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_r_grad_grad_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_r_grad_grad_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_t_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_t_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_t_grad_cpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_t_grad_gpu
Defined in File tabulate.h
Function Documentation
Template Function deepmd::tabulate_fusion_se_t_grad_grad_cpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_t_grad_grad_cpu(FPTYPE *dz_dy, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *dz_dy_dem_x, const FPTYPE *dz_dy_dem, const int nloc, const int nnei_i, const int nnei_j, const int last_layer_size)
Template Function deepmd::tabulate_fusion_se_t_grad_grad_gpu
Defined in File tabulate.h
Function Documentation
- template<typename FPTYPE>
void deepmd::tabulate_fusion_se_t_grad_grad_gpu(FPTYPE *dz_dy, const FPTYPE *table, const FPTYPE *table_info, const FPTYPE *em_x, const FPTYPE *em, const FPTYPE *dz_dy_dem_x, const FPTYPE *dz_dy_dem, const int nloc, const int nnei_i, const int nnei_j, const int last_layer_size)
Template Function deepmd::test_encoding_decoding_nbor_info_gpu
Defined in File fmt_nlist.h
Function Documentation
Function deepmd::use_nei_info_cpu
Defined in File neighbor_list.h
Function Documentation
- void deepmd::use_nei_info_cpu(int *nlist, int *ntype, bool *nmask, const int *type, const int *nlist_map, const int nloc, const int nnei, const int ntypes, const bool b_nlist_map)
Function deepmd::use_nei_info_gpu
Defined in File neighbor_list.h
Function Documentation
- void deepmd::use_nei_info_gpu(int *nlist, int *ntype, bool *nmask, const int *type, const int *nlist_map, const int nloc, const int nnei, const int ntypes, const bool b_nlist_map)
Function deepmd::use_nlist_map
Defined in File neighbor_list.h
Function Documentation
- void deepmd::use_nlist_map(int *nlist, const int *nlist_map, const int nloc, const int nnei)
Template Function deepmd::volume_cpu
Defined in File region.h
Function Documentation
Template Function deepmd::volume_gpu
Defined in File region.h
Function Documentation
Template Function dotmul_flt_nvnmd
Defined in File env_mat_nvnmd.h
Function Documentation
Function DPAssert(cudaError_t, const char *, int, bool)
Defined in File gpu_cuda.h
Function Documentation
- inline void DPAssert(cudaError_t code, const char *file, int line, bool abort = true)
Function DPAssert(hipError_t, const char *, int, bool)
Defined in File gpu_rocm.h
Function Documentation
- inline void DPAssert(hipError_t code, const char *file, int line, bool abort = true)
Function env_mat_a
Defined in File env_mat.h
Function Documentation
- void env_mat_a(std::vector<double> &descrpt_a, std::vector<double> &descrpt_a_deriv, std::vector<double> &rij_a, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const int &i_idx, const std::vector<int> &fmt_nlist, const std::vector<int> &sec, const double &rmin, const double &rmax)
Function env_mat_r
Defined in File env_mat.h
Function Documentation
- void env_mat_r(std::vector<double> &descrpt_r, std::vector<double> &descrpt_r_deriv, std::vector<double> &rij_r, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const int &i_idx, const std::vector<int> &fmt_nlist, const std::vector<int> &sec, const double &rmin, const double &rmax)
Template Function find_max_expo(int64_t&, T *, int64_t)
Defined in File env_mat_nvnmd.h
Function Documentation
Template Function find_max_expo(int64_t&, T *, int64_t, int64_t)
Defined in File env_mat_nvnmd.h
Function Documentation
Template Function format_nlist_i_cpu
Defined in File fmt_nlist.h
Function Documentation
Function format_nlist_i_fill_a
Defined in File fmt_nlist.h
Function Documentation
- int format_nlist_i_fill_a(std::vector<int> &fmt_nei_idx_a, std::vector<int> &fmt_nei_idx_r, const std::vector<double> &posi, const int &ntypes, const std::vector<int> &type, const SimulationRegion<double> ®ion, const bool &b_pbc, const int &i_idx, const std::vector<int> &nei_idx_a, const std::vector<int> &nei_idx_r, const double &rcut, const std::vector<int> &sec_a, const std::vector<int> &sec_r)
Template Function mul_flt_nvnmd
Defined in File env_mat_nvnmd.h
Function Documentation
Function nborAssert(cudaError_t, const char *, int, bool)
Defined in File gpu_cuda.h
Function Documentation
- inline void nborAssert(cudaError_t code, const char *file, int line, bool abort = true)
Function nborAssert(hipError_t, const char *, int, bool)
Defined in File gpu_rocm.h
Function Documentation
- inline void nborAssert(hipError_t code, const char *file, int line, bool abort = true)
Function omp_get_num_threads
Defined in File ewald.h
Function Documentation
- int omp_get_num_threads()
Function omp_get_thread_num
Defined in File ewald.h
Function Documentation
- int omp_get_thread_num()
Template Function split_flt
Defined in File env_mat_nvnmd.h
Function Documentation
Variables
Variable deepmd::ElectrostaticConvertion
Defined in File ewald.h
Variable Documentation
- const double deepmd::ElectrostaticConvertion = 14.39964535475696995031
Defines
Define DPErrcheck
Defined in File gpu_cuda.h
Define Documentation
- DPErrcheck(res)
Define DPErrcheck
Defined in File gpu_rocm.h
Define Documentation
- DPErrcheck(res)
Define FLT_MASK
Defined in File env_mat_nvnmd.h
Define Documentation
- FLT_MASK
Define GPU_MAX_NBOR_SIZE
Defined in File gpu_cuda.h
Define Documentation
- GPU_MAX_NBOR_SIZE
Define GPU_MAX_NBOR_SIZE
Defined in File gpu_rocm.h
Define Documentation
- GPU_MAX_NBOR_SIZE
Define gpuDeviceSynchronize
Defined in File gpu_cuda.h
Define Documentation
- gpuDeviceSynchronize
Define gpuDeviceSynchronize
Defined in File gpu_rocm.h
Define Documentation
- gpuDeviceSynchronize
Define gpuGetLastError
Defined in File gpu_cuda.h
Define Documentation
- gpuGetLastError
Define gpuGetLastError
Defined in File gpu_rocm.h
Define Documentation
- gpuGetLastError
Define gpuMemcpy
Defined in File gpu_cuda.h
Define Documentation
- gpuMemcpy
Define gpuMemcpy
Defined in File gpu_rocm.h
Define Documentation
- gpuMemcpy
Define gpuMemcpyDeviceToDevice
Defined in File gpu_cuda.h
Define Documentation
- gpuMemcpyDeviceToDevice
Define gpuMemcpyDeviceToDevice
Defined in File gpu_rocm.h
Define Documentation
- gpuMemcpyDeviceToDevice
Define gpuMemcpyDeviceToHost
Defined in File gpu_cuda.h
Define Documentation
- gpuMemcpyDeviceToHost
Define gpuMemcpyDeviceToHost
Defined in File gpu_rocm.h
Define Documentation
- gpuMemcpyDeviceToHost
Define gpuMemcpyHostToDevice
Defined in File gpu_cuda.h
Define Documentation
- gpuMemcpyHostToDevice
Define gpuMemcpyHostToDevice
Defined in File gpu_rocm.h
Define Documentation
- gpuMemcpyHostToDevice
Define gpuMemset
Defined in File gpu_cuda.h
Define Documentation
- gpuMemset
Define gpuMemset
Defined in File gpu_rocm.h
Define Documentation
- gpuMemset
Define MOASPNDIM
Defined in File SimulationRegion.h
Define Documentation
- MOASPNDIM
Define NBIT_CUTF
Defined in File env_mat_nvnmd.h
Define Documentation
- NBIT_CUTF
Define NBIT_FLTF
Defined in File env_mat_nvnmd.h
Define Documentation
- NBIT_FLTF
Define nborErrcheck
Defined in File gpu_cuda.h
Define Documentation
- nborErrcheck(res)
Define nborErrcheck
Defined in File gpu_rocm.h
Define Documentation
- nborErrcheck(res)
Define SQRT_2_PI
Defined in File device.h
Define Documentation
- SQRT_2_PI
Define TPB
Defined in File device.h
Define Documentation
- TPB
Typedefs
Typedef int_64
Defined in File device.h
Typedef Documentation
- typedef long long int_64
Typedef uint_64
Defined in File device.h
Typedef Documentation
- typedef unsigned long long uint_64
License
The project DeePMD-kit is licensed under GNU LGPLv3.0.
Logo
The logo of DeePMD-kit is a beaver. Beavers were widely distributed in Europe and Asia but became nearly extinct due to hunting. Listed as a first-class state-protected animal in China, the population of beavers in China is less than the giant pandas. We hope that users of DeePMD-kit can enhance the awareness to protect beavers.