Datasets:

ArXiv:
License:
siyuanliuseed commited on
Commit
731e53a
·
1 Parent(s): 31b14c7

update: model weights, evaluation script

Browse files
.gitattributes CHANGED
@@ -1 +1,3 @@
1
  *.lmdb filter=lfs diff=lfs merge=lfs -text
 
 
 
1
  *.lmdb filter=lfs diff=lfs merge=lfs -text
2
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
3
+ *.npz filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -34,6 +34,18 @@ We propose a framework for accelerating DFT calculations.
34
 
35
  We train E(3)-equivariant neural networks to predict the expansion coefficients of the electron density in an auxiliary basis, and use the prediction to construct an initial guess for the SCF process. This approach exhibits superior transferability in various aspects.
36
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # Contents
38
 
39
  The repo currently contains the following contents:
@@ -41,12 +53,8 @@ The repo currently contains the following contents:
41
  * The full SCFbench dataset.
42
  * The data pipeline for the SCFbench dataset.
43
  * The PyTorch `nn.Module` of the species-wise linear layer for the prediction of the electron density coefficients.
44
- * The NequIP model architecture with the species-wise linear layer.
45
  * Example code for computing the density coefficients from a density matrix.
46
-
47
- We will also release the following items soon:
48
-
49
- * The training code for models.
50
  * The full evaluation code.
51
 
52
 
@@ -92,6 +100,11 @@ dataset[0].keys()
92
  dataset.dataset[0].keys()
93
  ```
94
 
 
 
 
 
 
95
  # Citing SCFbench
96
  If you use SCFbench in your research, please cite:
97
  ```latex
 
34
 
35
  We train E(3)-equivariant neural networks to predict the expansion coefficients of the electron density in an auxiliary basis, and use the prediction to construct an initial guess for the SCF process. This approach exhibits superior transferability in various aspects.
36
 
37
+ # Changelog
38
+
39
+ ## 2026.3.7
40
+
41
+ * The full evaluation code is released.
42
+ * The train/valid/test split of the main dataset is released.
43
+ * The model weights of the NequIP model are released.
44
+
45
+ ## 2025.12.1
46
+
47
+ * First release.
48
+
49
  # Contents
50
 
51
  The repo currently contains the following contents:
 
53
  * The full SCFbench dataset.
54
  * The data pipeline for the SCFbench dataset.
55
  * The PyTorch `nn.Module` of the species-wise linear layer for the prediction of the electron density coefficients.
56
+ * The NequIP model code and weights with the species-wise linear layer.
57
  * Example code for computing the density coefficients from a density matrix.
 
 
 
 
58
  * The full evaluation code.
59
 
60
 
 
100
  dataset.dataset[0].keys()
101
  ```
102
 
103
+ # Evaluation
104
+
105
+ To evaluate
106
+
107
+
108
  # Citing SCFbench
109
  If you use SCFbench in your research, please cite:
110
  ```latex
dataset.py CHANGED
@@ -30,6 +30,25 @@ def compute_edge_index(coords, r_max, remove_self_loops=True):
30
  return edge_index
31
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  class ShardedLMDBDataset(Dataset):
34
  def __init__(self, data_root: str):
35
  super().__init__()
@@ -243,3 +262,48 @@ class SCFBenchDataset(Dataset):
243
  )
244
 
245
  return ret
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  return edge_index
31
 
32
 
33
+ def collate_key_nonindex(samples, key):
34
+ items = [s[key] for s in samples]
35
+ return torch.cat(items, dim=0)
36
+
37
+
38
+ def collate_key_index(samples, key, atom_index_cumsum, cat_dim):
39
+ return torch.cat([
40
+ s[key] + atom_index_cumsum[i]
41
+ for i, s in enumerate(samples)
42
+ ], dim=cat_dim)
43
+
44
+
45
+ def get_batch_vector(samples, node_level_key='z'):
46
+ natoms = [len(s[node_level_key]) for s in samples]
47
+ return torch.LongTensor([
48
+ isample for isample, n in enumerate(natoms) for _ in range(n)
49
+ ])
50
+
51
+
52
  class ShardedLMDBDataset(Dataset):
53
  def __init__(self, data_root: str):
54
  super().__init__()
 
262
  )
263
 
264
  return ret
265
+
266
+ def collater(self, samples):
267
+ batch = {}
268
+ batch.update({
269
+ key: collate_key_nonindex(samples, key)
270
+ for key in ['z', 'pos', 'net_charge', 'spin']
271
+ })
272
+
273
+ natoms = [len(s['z']) for s in samples]
274
+ atom_index_cumsum = [0] + list(np.cumsum(natoms))
275
+
276
+ if any(p.startswith('auxdensity') for p in self.parts_to_load):
277
+ batch.update({
278
+ 'auxdensity': {
279
+ key: collate_key_nonindex([s['auxdensity'] for s in samples], key)
280
+ for key in self.type_names
281
+ },
282
+ 'species_indices': {
283
+ key: collate_key_index([s['species_indices'] for s in samples], key, atom_index_cumsum, 0)
284
+ for key in self.type_names
285
+ },
286
+ })
287
+
288
+ if 'dm' in self.parts_to_load:
289
+ batch.update({
290
+ 'dm_diag_blocks': collate_key_nonindex(samples, 'dm_diag_blocks'),
291
+ 'dm_diag_masks': collate_key_nonindex(samples, 'dm_diag_masks'),
292
+ 'dm_tril_blocks': collate_key_nonindex(samples, 'dm_tril_blocks'),
293
+ 'dm_tril_masks': collate_key_nonindex(samples, 'dm_tril_masks'),
294
+ 'dm_tril_edge_index': collate_key_index(samples, 'dm_tril_edge_index', atom_index_cumsum, 1),
295
+ })
296
+
297
+ if 'fock' in self.parts_to_load:
298
+ batch.update({
299
+ 'fock_diag_blocks': collate_key_nonindex(samples, 'fock_diag_blocks'),
300
+ 'fock_diag_masks': collate_key_nonindex(samples, 'fock_diag_masks'),
301
+ 'fock_tril_blocks': collate_key_nonindex(samples, 'fock_tril_blocks'),
302
+ 'fock_tril_masks': collate_key_nonindex(samples, 'fock_tril_masks'),
303
+ 'fock_tril_edge_index': collate_key_index(samples, 'fock_tril_edge_index', atom_index_cumsum, 1),
304
+ })
305
+
306
+ batch['batch'] = get_batch_vector(samples, node_level_key='z')
307
+ batch['edge_index'] = collate_key_index(samples, 'edge_index', atom_index_cumsum, 1)
308
+ batch['bsz'] = len(samples)
309
+ return batch
evaluate_scf_gpu.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import argparse
5
+ from functools import partial
6
+
7
+ import tqdm
8
+ import numpy as np
9
+ import scipy
10
+ import pandas as pd
11
+
12
+ import torch
13
+ from torch.utils.data import DataLoader, Subset
14
+
15
+ import cupy as cp
16
+ import pyscf
17
+ import pyscf.df
18
+
19
+ from gto import GTOBasis, element_to_atomic_number, GTOProductBasisHelper, build_irreps_from_mol, pyscf_to_standard_perm_D
20
+ from dataset import SCFBenchDataset
21
+ from nequip_model import nequip_simple_builder
22
+
23
+
24
+ def move_data_to_device(data, device):
25
+ def move(x):
26
+ if isinstance(x, torch.Tensor):
27
+ return x.to(device)
28
+ elif isinstance(x, dict):
29
+ return {k: move(v) for k, v in x.items()}
30
+ else:
31
+ return x
32
+ return move(data)
33
+
34
+
35
+ def run_scf_and_count_steps(mol, xc, dm0=None, verbose=False, with_df=False, with_df_basis='def2-svp-jkfit'):
36
+ t_start = time.time()
37
+
38
+ mf = mol.RKS(xc=xc)
39
+ if with_df:
40
+ mf = mf.density_fit(auxbasis=with_df_basis)
41
+ mf = mf.to_gpu()
42
+ if verbose:
43
+ mf.verbose = 4
44
+ else:
45
+ mf.verbose = 0
46
+
47
+ mf.scf(dm0=dm0)
48
+ steps = mf.cycles if mf.converged else -1
49
+ e_tot = mf.e_tot
50
+
51
+ return e_tot, steps, time.time() - t_start
52
+
53
+
54
+ def transfer_fock(mol, transfer_mol, fock):
55
+ S_cross = pyscf.gto.mole.intor_cross('int1e_ovlp', mol, transfer_mol)
56
+ S1 = mol.intor('int1e_ovlp')
57
+ C = scipy.linalg.solve(S1, S_cross)
58
+ transfer_fock = C.T.dot(fock).dot(C)
59
+ return transfer_fock
60
+
61
+
62
+ def dm_from_fock(mol, overlap, fock):
63
+ # from QHNet
64
+ overlap = torch.tensor(overlap)
65
+ fock = torch.tensor(fock)
66
+ eigvals, eigvecs = torch.linalg.eigh(overlap)
67
+ eps = 1e-8 * torch.ones_like(eigvals)
68
+ eigvals = torch.where(eigvals > 1e-8, eigvals, eps)
69
+ frac_overlap = eigvecs / torch.sqrt(eigvals).unsqueeze(-2)
70
+
71
+ Fs = torch.mm(torch.mm(frac_overlap.transpose(-1, -2), fock), frac_overlap)
72
+ orbital_energies, orbital_coefficients = torch.linalg.eigh(Fs)
73
+ orbital_coefficients = torch.mm(frac_overlap, orbital_coefficients)
74
+ num_orb = mol.nelectron // 2
75
+ orbital_coefficients = orbital_coefficients.squeeze()
76
+ dm0 = orbital_coefficients[:, :num_orb].matmul(orbital_coefficients[:, :num_orb].T) * 2
77
+ dm0 = dm0.cpu().numpy()
78
+ return dm0
79
+
80
+
81
+ def dm_from_auxdensity(mol, auxmol, xc, aux_vec, normalize_nelec, transfer_mol=None):
82
+ import numpy
83
+ import cupy
84
+ from pyscf import lib
85
+ import gpu4pyscf.scf.jk
86
+ from gpu4pyscf.df.int3c2e_bdiv import Int3c2eOpt
87
+ from gpu4pyscf.lib.cupy_helper import contract
88
+ from gpu4pyscf.dft.numint import NumInt, add_sparse, _tau_dot, _scale_ao, _GDFTOpt
89
+ from gpu4pyscf.dft import Grids
90
+ from gpu4pyscf.lib.cupy_helper import transpose_sum
91
+
92
+ def nr_rks(xctype, mol, xc_code, auxmol, aux_vec):
93
+ # xctype = ni._xc_type(xc_code)
94
+ if xctype == 'LDA':
95
+ ao_deriv = 0
96
+ else:
97
+ ao_deriv = 1
98
+ comp = (ao_deriv+1)*(ao_deriv+2)*(ao_deriv+3)//6
99
+
100
+ grids = Grids(mol).build()
101
+ ngrids = grids.weights.size
102
+
103
+ rho = cupy.zeros((comp, ngrids))
104
+ aux_ni = NumInt().build(auxmol, grids)
105
+ naux = aux_ni.gdftopt._sorted_mol.nao
106
+ _sorted_aux_vec = aux_ni.gdftopt.sort_orbitals(aux_vec, axis=[0])
107
+
108
+ p0 = p1 = 0
109
+ for aux_ao_on_grids, idx, weight, _ in aux_ni.block_loop(aux_ni.gdftopt._sorted_mol, grids, naux, ao_deriv):
110
+ p0, p1 = p1, p1 + weight.size
111
+ rho[:,p0:p1] = (contract('xig,i->xg', aux_ao_on_grids, _sorted_aux_vec[idx]))
112
+
113
+ del aux_ao_on_grids, _sorted_aux_vec
114
+
115
+ grids = Grids(mol).build()
116
+ ni = NumInt().build(mol, grids)
117
+ if xctype == 'MGGA':
118
+ rho = cupy.vstack([rho, (rho[1:4]**2).sum(axis=0)/rho[0]/8])
119
+ weights = cupy.asarray(grids.weights)
120
+ nelec = rho[0].dot(weights)
121
+ exc, vxc = ni.eval_xc_eff(xc_code, rho, deriv=1, xctype=xctype)[:2]
122
+ vxc = cupy.asarray(vxc, order='C')
123
+ exc = cupy.asarray(exc, order='C')
124
+ excsum = float(cupy.dot(rho[0]*weights, exc[:,0]))
125
+ wv = vxc
126
+ wv *= weights
127
+ if xctype == 'GGA':
128
+ wv[0] *= .5
129
+ if xctype == 'MGGA':
130
+ wv[[0,4]] *= .5
131
+
132
+ opt = ni.gdftopt
133
+ _sorted_mol = opt._sorted_mol
134
+ nao = _sorted_mol.nao
135
+ buf = None
136
+ vtmp_buf = cupy.empty(nao*nao)
137
+ vmat = cupy.zeros((nao, nao))
138
+ p0 = p1 = 0
139
+ for ao_mask, idx, weight, _ in ni.block_loop(
140
+ _sorted_mol, grids, nao, ao_deriv, max_memory=None):
141
+ p0, p1 = p1, p1 + weight.size
142
+ nao_sub = len(idx)
143
+ vtmp = cupy.ndarray((nao_sub, nao_sub), memptr=vtmp_buf.data)
144
+ if xctype == 'LDA':
145
+ aow = _scale_ao(ao_mask, wv[0,p0:p1], out=buf)
146
+ add_sparse(vmat, ao_mask.dot(aow.T, out=vtmp), idx)
147
+ elif xctype == 'GGA':
148
+ aow = _scale_ao(ao_mask, wv[:,p0:p1], out=buf)
149
+ add_sparse(vmat, ao_mask[0].dot(aow.T, out=vtmp), idx)
150
+ elif xctype == 'MGGA':
151
+ vtmp = _tau_dot(ao_mask, ao_mask, wv[4,p0:p1], buf=buf, out=vtmp)
152
+ aow = _scale_ao(ao_mask, wv[:4,p0:p1], out=buf)
153
+ vtmp = contract('ig,jg->ij', ao_mask[0], aow, beta=1., out=vtmp)
154
+ add_sparse(vmat, vtmp, idx)
155
+ vmat = opt.unsort_orbitals(vmat, axis=[0,1])
156
+ if xctype != 'LDA':
157
+ transpose_sum(vmat)
158
+ return nelec, excsum, vmat
159
+
160
+ def get_j(mol, auxmol, aux_vec):
161
+ int3c2e_opt = Int3c2eOpt(mol, auxmol).build()
162
+ aux_vec_sorted = cupy.asarray(int3c2e_opt.aux_coeff).dot(cupy.asarray(aux_vec))
163
+ p1 = 0
164
+ J_compressed = 0
165
+ for eri3c in int3c2e_opt.int3c2e_bdiv_generator(batch_size=1200):
166
+ p0, p1 = p1, p1 + eri3c.shape[1]
167
+ J_compressed += eri3c.dot(aux_vec_sorted[p0:p1])
168
+ nao = int3c2e_opt.sorted_mol.nao
169
+ J = cupy.zeros((nao, nao))
170
+ ao_pair_mapping = int3c2e_opt.create_ao_pair_mapping()
171
+ rows, cols = divmod(cupy.asarray(ao_pair_mapping), nao)
172
+ J[rows, cols] = J[cols, rows] = J_compressed
173
+ c = cupy.asarray(int3c2e_opt.coeff)
174
+ return c.T.dot(J).dot(c)
175
+
176
+ def get_jk(mol, dm, auxmol, aux_vec):
177
+ vj = get_j(mol, auxmol, aux_vec)
178
+ _, vk = gpu4pyscf.scf.jk.get_jk(mol, dm, 1, with_j=False)
179
+ return vj, vk
180
+
181
+ def get_veff(ks, auxmol, aux_vec, dm, mol=None, hermi=1):
182
+ time_stats = {}
183
+ if mol is None: mol = ks.mol
184
+ ni = ks._numint
185
+ if hermi == 2: # because rho = 0
186
+ n, exc, vxc = 0, 0, 0
187
+ else:
188
+ # no memory check
189
+ # max_memory = ks.max_memory - lib.current_memory()[0]
190
+ t_start = time.time()
191
+ n, exc, vxc = nr_rks(ni._xc_type(ks.xc), mol, ks.xc, auxmol, aux_vec)
192
+ time_stats['grid_eval_time'] = time.time() - t_start
193
+ if ks.do_nlc():
194
+ raise NotImplementedError
195
+ if not ni.libxc.is_hybrid_xc(ks.xc):
196
+ t_start = time.time()
197
+ vj = get_j(mol, auxmol, aux_vec)
198
+ time_stats['get_j_time'] = time.time() - t_start
199
+ vxc += vj
200
+ else:
201
+ omega, alpha, hyb = ni.rsh_and_hybrid_coeff(ks.xc, spin=mol.spin)
202
+ if omega == 0:
203
+ vj, vk = get_jk(mol, dm, auxmol, aux_vec)
204
+ vk *= hyb
205
+ else:
206
+ raise NotImplementedError
207
+ vxc += vj - vk * .5
208
+ return vxc, time_stats
209
+
210
+ def int1e1c_analytical(mol):
211
+ """
212
+ Calculate integral values
213
+ .. math:: \int_{-\infty}^{\infty} phi(r) dr
214
+ """
215
+ integral_val = []
216
+ for idx, aug_mom in enumerate(mol._bas[:, 1]):
217
+ if aug_mom == 0:
218
+ exponents = mol.bas_exp(idx)
219
+ norm = (2 * exponents / numpy.pi)**0.75
220
+ coeffs = mol.bas_ctr_coeff(idx)[:, 0]
221
+ integral_val.append(
222
+ (coeffs * norm * (numpy.pi / exponents)**1.5).sum())
223
+ else:
224
+ integral_val += [0] * (2*aug_mom+1)
225
+ integral_val = numpy.array(integral_val)
226
+ return integral_val
227
+
228
+ extra_stats = {}
229
+
230
+ if normalize_nelec:
231
+ aux_1c1e = cp.array(int1e1c_analytical(auxmol))
232
+ aux_vec_nelec = aux_vec @ aux_1c1e
233
+ aux_vec *= mol.nelectron / aux_vec_nelec
234
+ extra_stats['aux_vec_nelec'] = aux_vec_nelec.get().item()
235
+
236
+ mf = mol.RKS(xc=xc).to_gpu()
237
+
238
+ dm_guess = 0
239
+ if mf._numint.libxc.is_hybrid_xc(mf.xc):
240
+ dm_guess = mf.get_init_guess()
241
+
242
+ fock, veff_time_stats = get_veff(mf, auxmol, aux_vec, dm_guess)
243
+ fock = fock + mf.get_hcore()
244
+ extra_stats.update(veff_time_stats)
245
+
246
+ if transfer_mol is not None:
247
+ fock = cupy.array(transfer_fock(mol, transfer_mol, fock.get()))
248
+ mol = transfer_mol
249
+
250
+ t_start = time.time()
251
+ s1e = mol.intor('int1e_ovlp')
252
+ mo_energy, mo_coeff = gpu4pyscf.lib.cupy_helper.eigh(cupy.array(fock), cupy.array(s1e))
253
+ extra_stats['eigh_time'] = time.time() - t_start
254
+ nocc = mol.nelectron // 2
255
+ mocc = mo_coeff[:,:nocc]
256
+ dm0 = mocc.dot(mocc.conj().T) * 2
257
+ dm0_numpy = dm0.get()
258
+ return dm0_numpy, extra_stats
259
+
260
+
261
+ def build_mol_from_data(type_names, aobasis_name, data):
262
+ nuclei = [element_to_atomic_number[type_names[z]] for z in data['z'].cpu().numpy()]
263
+ coords = data['pos'].cpu().numpy()
264
+ mol = pyscf.M(atom=list(zip(nuclei, coords)), basis=aobasis_name)
265
+ return mol
266
+
267
+
268
+ def pred_auxdensity_postprocess(mol, outputs, auxbasis_name, auxbasis, xc, use_denfit_ovlp, normalize_nelec, transfer_mol=None):
269
+ t0 = time.time()
270
+ preds = outputs['output:auxdensity']
271
+ if auxbasis_name.startswith('etb:'):
272
+ beta = float(auxbasis_name.split(':')[-1])
273
+ etb_basis = pyscf.df.aug_etb(mol, beta)
274
+ auxmol = pyscf.df.make_auxmol(mol, auxbasis=etb_basis)
275
+ else:
276
+ auxmol = pyscf.df.make_auxmol(mol, auxbasis=auxbasis_name)
277
+ atom_count_by_elements = {k: 0 for k in preds.keys()}
278
+ atom_vecs = []
279
+ for iatm in range(mol.natm):
280
+ symbol = mol.atom_pure_symbol(iatm)
281
+ atom_vecs.append(preds[symbol][atom_count_by_elements[symbol]])
282
+ atom_count_by_elements[symbol] += 1
283
+ aux_vec = torch.cat(atom_vecs)
284
+ mol_irreps = build_irreps_from_mol(auxmol)
285
+ aux_vec = pyscf_to_standard_perm_D(mol_irreps).T.to(aux_vec) @ aux_vec
286
+ aux_vec = aux_vec.cpu().numpy()
287
+ if use_denfit_ovlp:
288
+ aux_vec = np.linalg.solve(auxmol.intor('int1e_ovlp'), aux_vec)
289
+ t1 = time.time()
290
+ # dm = dm_from_auxdensity(mol, auxmol, xc, aux_vec, normalize_nelec, transfer_mol)
291
+ dm, time_stats = dm_from_auxdensity(mol, auxmol, xc, cp.array(aux_vec), normalize_nelec, transfer_mol)
292
+ time_stats['model_to_auxvec_time'] = t1 - t0
293
+ return dm, time_stats
294
+
295
+
296
+ def pred_fock_postprocess(mol, outputs, ao_prod_basis, normalize_nelec, transfer_mol=None):
297
+ fock = ao_prod_basis.assemble_matrix_from_padded_blocks(mol.atom_charges(), outputs['output:fock_diag_blocks'].cpu().numpy(), outputs['output:fock_tril_blocks'].cpu().numpy())
298
+ fock = ao_prod_basis.transform_from_std_to_pyscf(mol.atom_charges(), fock)
299
+
300
+ if transfer_mol is None:
301
+ overlap = mol.intor('int1e_ovlp').astype(np.float32)
302
+ dm = dm_from_fock(mol, overlap, fock)
303
+ else:
304
+ overlap = transfer_mol.intor('int1e_ovlp')
305
+ transfer_fock = transfer_fock(mol, transfer_mol, fock)
306
+ dm = dm_from_fock(transfer_mol, overlap, transfer_fock)
307
+
308
+ if normalize_nelec:
309
+ dm *= mol.nelectron / (dm * overlap).sum()
310
+
311
+ return dm, {}
312
+
313
+
314
+ def pred_dm_postprocess(mol, outputs, ao_prod_basis, normalize_nelec, transfer_mol=None):
315
+ dm = ao_prod_basis.assemble_matrix_from_padded_blocks(mol.atom_charges(), outputs['output:dm_diag_blocks'].cpu().numpy(), outputs['output:dm_tril_blocks'].cpu().numpy())
316
+ dm = ao_prod_basis.transform_from_std_to_pyscf(mol.atom_charges(), dm)
317
+
318
+ if normalize_nelec:
319
+ overlap = mol.intor('int1e_ovlp').astype(np.float32)
320
+ dm *= mol.nelectron / (dm * overlap).sum()
321
+ if transfer_mol is not None:
322
+ raise NotImplementedError
323
+ return dm, {}
324
+
325
+
326
+ def main():
327
+ parser = argparse.ArgumentParser()
328
+ parser.add_argument('--ckpt', type=str, help='Path to the checkpoint file')
329
+ parser.add_argument('--gt-mode', action='store_true', help='Use ground truth as initial guess.')
330
+ parser.add_argument('--data-root', default='./dataset/ood-test', type=str, help='Path to the data root directory')
331
+ parser.add_argument('--model-type', default='auxdensity', type=str, choices=['auxdensity', 'dm', 'fock'], help='Prediction type of the model')
332
+ parser.add_argument('--xc', default='PBE', type=str, help='XC functional')
333
+ parser.add_argument('--transfer-basis', default=None, type=str, help='Basis set to which the model prediction is transferred to.')
334
+ parser.add_argument('--with-df', action='store_true', help='Use density fitting for SCF.')
335
+ parser.add_argument('--with-df-basis', default='def2-svp-jkfit', help='The basis set for density fitting in SCF.')
336
+ parser.add_argument('--output', required=True, type=str, help='Path to the output CSV file')
337
+ parser.add_argument('--num-shards', type=int, default=1, help='Number of shards')
338
+ parser.add_argument('--shard-index', default=0, type=int, help='Shard index')
339
+ parser.add_argument('--scf-verbose', action='store_true', help='Print SCF verbose information')
340
+ parser.add_argument('--split', default='no', type=str, choices=['train', 'val', 'test', 'no'], help='Split of the dataset')
341
+ parser.add_argument('--normalize-nelec', action='store_true', help='Normalize the model prediction by number of electrons.')
342
+ args = parser.parse_args()
343
+
344
+ if not args.gt_mode:
345
+ assert args.ckpt is not None, 'Checkpoint path is required in non-gt mode.'
346
+
347
+ ckpt = torch.load(args.ckpt, map_location='cpu', weights_only=True)
348
+
349
+ config = ckpt['config']
350
+ model = nequip_simple_builder(**config['model'])
351
+ model.load_state_dict(ckpt['state_dict'])
352
+ model = model.eval().cuda()
353
+ data_config = config['data']
354
+ else:
355
+ gt_mode_part = 'auxdensity.denfit' if args.model_type == 'auxdensity' else args.model_type
356
+ data_config = {
357
+ 'r_max': 5.0,
358
+ 'type_names': ['H', 'C', 'N', 'O', 'F', 'P', 'S'],
359
+ 'remove_self_loops': True,
360
+ 'parts_to_load': ['base', gt_mode_part],
361
+ 'aobasis': 'def2-svp',
362
+ 'auxbasis': 'def2-universal-jfit',
363
+ 'use_denfit_ovlp': False,
364
+ }
365
+
366
+ dataset = SCFBenchDataset(data_root=args.data_root, **data_config)
367
+ if args.split != 'no':
368
+ print(f'Assuming the dataset is SCFbench-main and using indices from scfbench_main_split.npz for split {args.split}...')
369
+ split_file = np.load('./scfbench_main_split.npz')
370
+ dataset_indices = split_file[args.split].tolist()
371
+ else:
372
+ dataset_indices = list(range(len(dataset)))
373
+
374
+ dataset_subset_indices = [i for i in dataset_indices if i % args.num_shards == args.shard_index]
375
+ dataloader = DataLoader(
376
+ Subset(dataset, dataset_subset_indices),
377
+ batch_size=1,
378
+ shuffle=False,
379
+ num_workers=2,
380
+ collate_fn=dataset.collater,
381
+ )
382
+
383
+ aobasis_name, auxbasis_name = data_config['aobasis'], data_config['auxbasis']
384
+
385
+ aobasis = GTOBasis.from_basis_name(aobasis_name, elements=data_config['type_names'])
386
+ auxbasis = GTOBasis.from_basis_name(auxbasis_name, elements=data_config['type_names'])
387
+ ao_prod_basis = GTOProductBasisHelper(aobasis)
388
+
389
+ use_denfit_ovlp = data_config.get('use_denfit_ovlp', False)
390
+
391
+ records = []
392
+ for data in tqdm.tqdm(dataloader):
393
+ data = move_data_to_device(data, 'cuda')
394
+
395
+ mol = build_mol_from_data(data_config['type_names'], aobasis_name, data)
396
+ transfer_mol = build_mol_from_data(data_config['type_names'], args.transfer_basis, data) if args.transfer_basis else None
397
+
398
+ if not args.gt_mode:
399
+ model_time = 1000.0
400
+ while model_time > 1:
401
+ t0 = time.time()
402
+ with torch.no_grad():
403
+ outputs = model(data)
404
+ t1 = time.time()
405
+ model_time = t1 - t0
406
+ else:
407
+ if args.model_type == 'auxdensity':
408
+ outputs = {'output:auxdensity': data['auxdensity']}
409
+ elif args.model_type == 'fock':
410
+ outputs = {'output:fock_diag_blocks': data['fock_diag_blocks'], 'output:fock_tril_blocks': data['fock_tril_blocks']}
411
+ elif args.model_type == 'dm':
412
+ outputs = {'output:dm_diag_blocks': data['dm_diag_blocks'], 'output:dm_tril_blocks': data['dm_tril_blocks']}
413
+ model_time = 0.0
414
+
415
+ t2 = time.time()
416
+
417
+ if args.model_type == 'auxdensity':
418
+ dm, extra_stats = pred_auxdensity_postprocess(mol, outputs, auxbasis_name, auxbasis, args.xc, use_denfit_ovlp, args.normalize_nelec, transfer_mol=transfer_mol)
419
+ elif args.model_type == 'fock':
420
+ dm, extra_stats = pred_fock_postprocess(mol, outputs, ao_prod_basis, args.normalize_nelec, transfer_mol=transfer_mol)
421
+ elif args.model_type == 'dm':
422
+ dm, extra_stats = pred_dm_postprocess(mol, outputs, ao_prod_basis, args.normalize_nelec, transfer_mol=transfer_mol)
423
+
424
+ t3 = time.time()
425
+
426
+ eval_scf = partial(run_scf_and_count_steps, xc=args.xc, verbose=args.scf_verbose, with_df=args.with_df, with_df_basis=args.with_df_basis)
427
+ if transfer_mol is not None:
428
+ original_energy, original_steps, original_time = eval_scf(transfer_mol, dm0=None)
429
+ accelerated_energy, accelerated_steps, accelerated_time = eval_scf(transfer_mol, dm0=cp.array(dm.astype(np.float64))) # the type conversion is important here
430
+ else:
431
+ original_energy, original_steps, original_time = eval_scf(mol, dm0=None)
432
+ accelerated_energy, accelerated_steps, accelerated_time = eval_scf(mol, dm0=cp.array(dm.astype(np.float64))) # the type conversion is important here
433
+
434
+ record = {
435
+ 'natom': mol.natm,
436
+ 'nelec': mol.nelectron,
437
+ 'original_steps': original_steps,
438
+ 'accelerated_steps': accelerated_steps,
439
+ 'original_time': original_time,
440
+ 'accelerated_time': accelerated_time,
441
+ 'original_energy': original_energy,
442
+ 'accelerated_energy': accelerated_energy,
443
+ 'model_time': model_time,
444
+ 'conversion_time': t3 - t2,
445
+ }
446
+ record.update(extra_stats)
447
+ print(record)
448
+ records.append(record)
449
+
450
+ del data, mol, dm, outputs
451
+
452
+ if len(records) % 10 == 0:
453
+ df = pd.DataFrame.from_records(records)
454
+ df.to_csv(args.output, index=False)
455
+
456
+ df = pd.DataFrame.from_records(records)
457
+ df.to_csv(args.output, index=False)
458
+
459
+
460
+ if __name__ == '__main__':
461
+ main()
nequip_L_jfit.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c76173949255069cd0862cc2859ebdd4c66d01a97474243946a31ab34f00137
3
+ size 202296215
nequip_model.py CHANGED
@@ -116,7 +116,6 @@ class NequipArch(nn.Module):
116
  convnet_nonlinearity_type: str = "gate",
117
  convnet_nonlinearity_scalars: dict[int, Callable] = {"e": "silu", "o": "tanh"},
118
  convnet_nonlinearity_gates: dict[int, Callable] = {"e": "silu", "o": "tanh"},
119
- task_head_specs: dict[str, Any] = {},
120
  auxbasis: str = "def2-universal-jfit",
121
  ):
122
  super().__init__()
 
116
  convnet_nonlinearity_type: str = "gate",
117
  convnet_nonlinearity_scalars: dict[int, Callable] = {"e": "silu", "o": "tanh"},
118
  convnet_nonlinearity_gates: dict[int, Callable] = {"e": "silu", "o": "tanh"},
 
119
  auxbasis: str = "def2-universal-jfit",
120
  ):
121
  super().__init__()
scfbench_main_split.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0cf7e22feda869fab3825e53cb5c9d67a079db5cdd79fd505c4bab4982fdc651
3
+ size 351634