se_a.py 10.8 KB
Newer Older
zhangqha's avatar
zhangqha committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import numpy as np

from deepmd.env import tf
from deepmd.env import GLOBAL_TF_FLOAT_PRECISION
from deepmd.env import GLOBAL_NP_FLOAT_PRECISION
from deepmd.env import op_module
from deepmd.utils.network import embedding_net


#
from deepmd.nvnmd.utils.config import nvnmd_cfg
from deepmd.nvnmd.utils.network import matmul3_qq
from deepmd.nvnmd.utils.weight import get_normalize, get_rng_s


def build_davg_dstd():
    r"""Get the davg and dstd from the dictionary nvnmd_cfg.
    The davg and dstd have been obtained by training CNN
    """
    davg, dstd = get_normalize(nvnmd_cfg.weight)
    return davg, dstd


def build_op_descriptor():
    r"""Replace se_a.py/DescrptSeA/build
    """
    if nvnmd_cfg.quantize_descriptor:
        return op_module.prod_env_mat_a_nvnmd_quantize
    else:
        return op_module.prod_env_mat_a


def descrpt2r4(inputs, natoms):
    r"""Replace :math:`r_{ji} \rightarrow r'_{ji}`
    where :math:`r_{ji} = (x_{ji}, y_{ji}, z_{ji})` and
    :math:`r'_{ji} = (s_{ji}, \frac{s_{ji} x_{ji}}{r_{ji}}, \frac{s_{ji} y_{ji}}{r_{ji}}, \frac{s_{ji} z_{ji}}{r_{ji}})`
    """
    NBIT_DATA_FL = nvnmd_cfg.nbit['NBIT_DATA_FL']
    NBIT_FEA_X_FL = nvnmd_cfg.nbit['NBIT_FEA_X_FL']
    NBIT_FEA_FL = nvnmd_cfg.nbit['NBIT_FEA_FL']
    prec = 1.0 / (2 ** NBIT_FEA_X_FL)

    ntypes = nvnmd_cfg.dscp['ntype']
    NIDP = nvnmd_cfg.dscp['NIDP']
    ndescrpt = NIDP * 4
    start_index = 0

    # (nf, na*nd)
    shape = inputs.get_shape().as_list()
    # (nf*na*ni, 4)
    inputs_reshape = tf.reshape(inputs, [-1, 4])

    with tf.variable_scope('filter_type_all_x', reuse=True):
        # u (i.e., r^2)
        u = tf.reshape(tf.slice(inputs_reshape, [0, 0], [-1, 1]), [-1, 1])
        with tf.variable_scope('u', reuse=True):
            u = op_module.quantize_nvnmd(u, 0, -1, NBIT_DATA_FL, -1)
        # print('u:', u)
        u = tf.reshape(u, [-1, natoms[0] * NIDP])
        # rij
        rij = tf.reshape(tf.slice(inputs_reshape, [0, 1], [-1, 3]), [-1, 3])
        with tf.variable_scope('rij', reuse=True):
            rij = op_module.quantize_nvnmd(rij, 0, NBIT_DATA_FL, -1, -1)
        # print('rij:', rij)
        s = []
        sr = []
        for type_i in range(ntypes):
            type_input = 0
            postfix = f"_t{type_input}_t{type_i}"
            u_i = tf.slice(
                u,
                [0, start_index * NIDP],
                [-1, natoms[2 + type_i] * NIDP])
            u_i = tf.reshape(u_i, [-1, 1])
            #
            keys = 's,sr'.split(',')
            map_tables = [nvnmd_cfg.map[key + postfix] for key in keys]
            map_tables2 = [nvnmd_cfg.map[f"d{key}_dr2" + postfix] for key in keys]
            map_outs = []
            for ii in range(len(keys)):
                map_outs.append(op_module.map_nvnmd(
                    u_i,
                    map_tables[ii][0],
                    map_tables[ii][1] / prec,
                    map_tables2[ii][0],
                    map_tables2[ii][1] / prec,
                    prec, NBIT_FEA_FL))

            s_i, sr_i = map_outs
            s_i = tf.reshape(s_i, [-1, natoms[2 + type_i] * NIDP])
            sr_i = tf.reshape(sr_i, [-1, natoms[2 + type_i] * NIDP])
            s.append(s_i)
            sr.append(sr_i)
            start_index += natoms[2 + type_i]

        s = tf.concat(s, axis=1)
        sr = tf.concat(sr, axis=1)

        with tf.variable_scope('s', reuse=True):
            s = op_module.quantize_nvnmd(s, 0, NBIT_FEA_FL, NBIT_DATA_FL, -1)

        with tf.variable_scope('sr', reuse=True):
            sr = op_module.quantize_nvnmd(sr, 0, NBIT_FEA_FL, NBIT_DATA_FL, -1)

        s = tf.reshape(s, [-1, 1])
        sr = tf.reshape(sr, [-1, 1])

        # R2R4
        Rs = s
        Rxyz = sr * rij
        with tf.variable_scope('Rxyz', reuse=True):
            Rxyz = op_module.quantize_nvnmd(Rxyz, 0, NBIT_DATA_FL, NBIT_DATA_FL, -1)
        R4 = tf.concat([Rs, Rxyz], axis=1)
        R4 = tf.reshape(R4, [-1, NIDP, 4])
        inputs_reshape = R4
        inputs_reshape = tf.reshape(inputs_reshape, [-1, ndescrpt])
    return inputs_reshape


def filter_lower_R42GR(
        type_i,
        type_input,
        inputs_i,
        is_exclude,
        activation_fn,
        bavg,
        stddev,
        trainable,
        suffix,
        seed,
        seed_shift,
        uniform_seed,
        filter_neuron,
        filter_precision,
        filter_resnet_dt,
        embedding_net_variables):
    r"""Replace se_a.py/DescrptSeA/_filter_lower
    """
    shape_i = inputs_i.get_shape().as_list()
    inputs_reshape = tf.reshape(inputs_i, [-1, 4])
    natom = tf.shape(inputs_i)[0]
    M1 = nvnmd_cfg.dscp['M1']

    NBIT_DATA_FL = nvnmd_cfg.nbit['NBIT_DATA_FL']
    NBIT_FEA_X_FL = nvnmd_cfg.nbit['NBIT_FEA_X_FL']
    NBIT_FEA_X2_FL = nvnmd_cfg.nbit['NBIT_FEA_X2_FL']
    NBIT_FEA_FL = nvnmd_cfg.nbit['NBIT_FEA_FL']
    prec = 1.0 / (2 ** NBIT_FEA_X2_FL)
    type_input = 0 if (type_input < 0) else type_input
    postfix = f"_t{type_input}_t{type_i}"

    if (nvnmd_cfg.quantize_descriptor):
        s_min, smax = get_rng_s(nvnmd_cfg.weight)
        s_min = -2.0
        # s_min = np.floor(s_min)
        s = tf.reshape(tf.slice(inputs_reshape, [0, 0], [-1, 1]), [-1, 1])
        s = op_module.quantize_nvnmd(s, 0, NBIT_FEA_FL, NBIT_DATA_FL, -1)
        # G
        keys = 'G'.split(',')
        map_tables = [nvnmd_cfg.map[key + postfix] for key in keys]
        map_tables2 = [nvnmd_cfg.map[f"d{key}_ds" + postfix] for key in keys]
        map_outs = []
        for ii in range(len(keys)):
            with tf.variable_scope(keys[ii], reuse=True):
                map_outs.append(op_module.map_nvnmd(
                    s - s_min,
                    map_tables[ii][0], map_tables[ii][1] / prec,
                    map_tables2[ii][0], map_tables2[ii][1] / prec,
                    prec, NBIT_FEA_FL))
                map_outs[ii] = op_module.quantize_nvnmd(map_outs[ii], 0, NBIT_FEA_FL, NBIT_DATA_FL, -1)
        G = map_outs
        # G
        xyz_scatter = G
        xyz_scatter = tf.reshape(xyz_scatter, (-1, shape_i[1] // 4, M1))
        # GR
        inputs_reshape = tf.reshape(inputs_reshape, [-1, shape_i[1] // 4, 4])
        GR = matmul3_qq(tf.transpose(inputs_reshape, [0, 2, 1]), xyz_scatter, -1)
        GR = tf.reshape(GR, [-1, 4 * M1])
        return GR

    else:
        xyz_scatter = tf.reshape(tf.slice(inputs_reshape, [0, 0], [-1, 1]), [-1, 1])
        if nvnmd_cfg.restore_descriptor:
            trainable = False
            embedding_net_variables = {}
            for key in nvnmd_cfg.weight.keys():
                if 'filter_type' in key:
                    key2 = key.replace('.', '/')
                    embedding_net_variables[key2] = nvnmd_cfg.weight[key]

        if (not is_exclude):
            xyz_scatter = embedding_net(
                xyz_scatter,
                filter_neuron,
                filter_precision,
                activation_fn=activation_fn,
                resnet_dt=filter_resnet_dt,
                name_suffix=suffix,
                stddev=stddev,
                bavg=bavg,
                seed=seed,
                trainable=trainable,
                uniform_seed=uniform_seed,
                initial_variables=embedding_net_variables)
            if (not uniform_seed) and (seed is not None):
                seed += seed_shift
        else:
            # we can safely return the final xyz_scatter filled with zero directly
            return tf.cast(tf.fill((natom, 4, M1), 0.), GLOBAL_TF_FLOAT_PRECISION)
        # natom x nei_type_i x out_size
        xyz_scatter = tf.reshape(xyz_scatter, (-1, shape_i[1] // 4, M1))
        # When using tf.reshape(inputs_i, [-1, shape_i[1]//4, 4]) below
        # [588 24] -> [588 6 4] correct
        # but if sel is zero
        # [588 0] -> [147 0 4] incorrect; the correct one is [588 0 4]
        # So we need to explicitly assign the shape to tf.shape(inputs_i)[0] instead of -1
        return tf.matmul(tf.reshape(inputs_i, [natom, shape_i[1] // 4, 4]), xyz_scatter, transpose_a=True)


def filter_GR2D(xyz_scatter_1):
    r"""Replace se_a.py/_filter
    """
    NIX = nvnmd_cfg.dscp['NIX']
    NBIT_DATA_FL = nvnmd_cfg.nbit['NBIT_DATA_FL']
    M1 = nvnmd_cfg.dscp['M1']
    M2 = nvnmd_cfg.dscp['M2']

    if (nvnmd_cfg.quantize_descriptor):
        xyz_scatter_1 = tf.reshape(xyz_scatter_1, [-1, 4 * M1])
        # fix the number of bits of gradient
        xyz_scatter_1 = op_module.quantize_nvnmd(xyz_scatter_1, 0, -1, NBIT_DATA_FL, -1)
        xyz_scatter_1 = xyz_scatter_1 * (1.0 / NIX)
        with tf.variable_scope('GR', reuse=True):
            xyz_scatter_1 = op_module.quantize_nvnmd(xyz_scatter_1, 0, NBIT_DATA_FL, NBIT_DATA_FL, -1)
        xyz_scatter_1 = tf.reshape(xyz_scatter_1, [-1, 4, M1])

        # natom x 4 x outputs_size_2
        xyz_scatter_2 = xyz_scatter_1
        # natom x 3 x outputs_size_1
        qmat = tf.slice(xyz_scatter_1, [0, 1, 0], [-1, 3, -1])
        # natom x outputs_size_2 x 3
        qmat = tf.transpose(qmat, perm=[0, 2, 1])
        # D': natom x outputs_size x outputs_size_2
        result = tf.matmul(xyz_scatter_1, xyz_scatter_2, transpose_a=True)
        # D': natom x (outputs_size x outputs_size_2)
        result = tf.reshape(result, [-1, M1 * M1])
        #
        index_subset = []
        for ii in range(M1):
            for jj in range(ii, ii + M2):
                index_subset.append((ii * M1) + (jj % M1))
        index_subset = tf.constant(np.int32(np.array(index_subset)))
        result = tf.gather(result, index_subset, axis=1)

        with tf.variable_scope('d', reuse=True):
            result = op_module.quantize_nvnmd(result, 0, NBIT_DATA_FL, NBIT_DATA_FL, -1)
    else:
        # natom x 4 x outputs_size
        xyz_scatter_1 = xyz_scatter_1 * (1.0 / NIX)
        # natom x 4 x outputs_size_2
        # xyz_scatter_2 = tf.slice(xyz_scatter_1, [0,0,0],[-1,-1,outputs_size_2])
        xyz_scatter_2 = xyz_scatter_1
        # natom x 3 x outputs_size_1
        qmat = tf.slice(xyz_scatter_1, [0, 1, 0], [-1, 3, -1])
        # natom x outputs_size_1 x 3
        qmat = tf.transpose(qmat, perm=[0, 2, 1])
        # natom x outputs_size x outputs_size_2
        result = tf.matmul(xyz_scatter_1, xyz_scatter_2, transpose_a=True)
        # natom x (outputs_size x outputs_size_2)
        # result = tf.reshape(result, [-1, outputs_size_2 * outputs_size[-1]])
        result = tf.reshape(result, [-1, M1 * M1])
        #
        index_subset = []
        for ii in range(M1):
            for jj in range(ii, ii + M2):
                index_subset.append((ii * M1) + (jj % M1))
        index_subset = tf.constant(np.int32(np.array(index_subset)))
        result = tf.gather(result, index_subset, axis=1)

    return result, qmat