Delete example_inference.py
Browse files- example_inference.py +0 -149
example_inference.py
DELETED
|
@@ -1,149 +0,0 @@
|
|
| 1 |
-
from typing import Dict, List, Optional, Tuple
|
| 2 |
-
from omegaconf import ListConfig
|
| 3 |
-
import os
|
| 4 |
-
import torch
|
| 5 |
-
from torch_geometric.data import Batch
|
| 6 |
-
from nets.equiformer_v2.equiformer_v2_oc20 import EquiformerV2_OC20
|
| 7 |
-
from nets.prediction_utils import compute_extra_props
|
| 8 |
-
import yaml
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
def get_model(config_path):
|
| 12 |
-
with open(config_path, "r") as file:
|
| 13 |
-
config = yaml.safe_load(file)
|
| 14 |
-
model_config = config["model"]
|
| 15 |
-
return EquiformerV2_OC20(**model_config), model_config
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
def predict(batch, potential):
|
| 19 |
-
"""Predict one or multiple batches"""
|
| 20 |
-
batch = batch.to(potential.device)
|
| 21 |
-
batch = compute_extra_props(batch, pos_require_grad=False)
|
| 22 |
-
energy, forces, eigenpred = potential.forward(batch, eigen=True)
|
| 23 |
-
return energy, forces, eigenpred
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def predict_with_hessian(batch, potential):
|
| 27 |
-
"""Predict one batch with autodiff Hessian"""
|
| 28 |
-
B = batch.batch.max() + 1
|
| 29 |
-
assert B == 1, "Only one batch is supported for Hessian prediction"
|
| 30 |
-
|
| 31 |
-
batch = batch.to(potential.device)
|
| 32 |
-
|
| 33 |
-
# Prepare batch with extra properties
|
| 34 |
-
batch = compute_extra_props(batch, pos_require_grad=True)
|
| 35 |
-
|
| 36 |
-
# Run prediction
|
| 37 |
-
with torch.enable_grad():
|
| 38 |
-
energy, forces, eigenpred = potential.forward(batch, eigen=True)
|
| 39 |
-
|
| 40 |
-
# 3D coordinates -> 3N^2 Hessian elements
|
| 41 |
-
N = batch.pos.shape[0]
|
| 42 |
-
forces = forces.reshape(-1)
|
| 43 |
-
num_elements = forces.shape[0]
|
| 44 |
-
|
| 45 |
-
def get_vjp(v):
|
| 46 |
-
return torch.autograd.grad(
|
| 47 |
-
outputs=-1 * forces,
|
| 48 |
-
inputs=batch.pos,
|
| 49 |
-
grad_outputs=v,
|
| 50 |
-
retain_graph=True,
|
| 51 |
-
create_graph=False,
|
| 52 |
-
allow_unused=False,
|
| 53 |
-
)
|
| 54 |
-
|
| 55 |
-
I_N = torch.eye(num_elements, device=forces.device)
|
| 56 |
-
hessian = torch.vmap(get_vjp, in_dims=0, out_dims=0, chunk_size=None)(I_N)[0]
|
| 57 |
-
hessian = hessian.view(N * 3, N * 3)
|
| 58 |
-
|
| 59 |
-
eigenvalues, eigenvectors = torch.linalg.eigh(hessian)
|
| 60 |
-
smallest_eigenvals = eigenvalues[:2]
|
| 61 |
-
smallest_eigenvecs = eigenvectors[:, :2]
|
| 62 |
-
eigenvalues = smallest_eigenvals
|
| 63 |
-
eigenvectors = smallest_eigenvecs.T.view(2, N, 3)
|
| 64 |
-
return energy, forces, hessian, eigenvalues, eigenvectors, eigenpred
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
def predict_gad(batch, potential):
|
| 68 |
-
B = batch.batch.max() + 1
|
| 69 |
-
energy, forces, eigenpred = predict(batch, potential)
|
| 70 |
-
v = eigenpred["eigvec_1"].reshape(B, -1)
|
| 71 |
-
v = v / torch.norm(v, dim=1, keepdim=True)
|
| 72 |
-
forces = forces.reshape(B, -1)
|
| 73 |
-
# −∇V(x) + 2(∇V, v(x))v(x)
|
| 74 |
-
gad = forces + 2 * torch.einsum("bi,bi->b", -forces, v) * v
|
| 75 |
-
return gad
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def predict_gad_with_hessian(batch, potential):
|
| 79 |
-
energy, forces, hessian, eigenvalues, eigenvectors, eigenpred = (
|
| 80 |
-
predict_with_hessian(batch, potential)
|
| 81 |
-
)
|
| 82 |
-
v = eigenvectors[0].reshape(-1) # N*3
|
| 83 |
-
v = v / torch.norm(v, dim=0, keepdim=True)
|
| 84 |
-
forces = forces.reshape(-1) # N*3
|
| 85 |
-
# −∇V(x) + 2(∇V, v(x))v(x)
|
| 86 |
-
gad = forces + 2 * torch.einsum("i,i->", -forces, v) * v
|
| 87 |
-
return gad
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
if __name__ == "__main__":
|
| 91 |
-
from torch_geometric.data import Data as TGData
|
| 92 |
-
from torch_geometric.loader import DataLoader as TGDataLoader
|
| 93 |
-
|
| 94 |
-
# you might need to change this
|
| 95 |
-
project_root = os.path.dirname(os.path.dirname(__file__))
|
| 96 |
-
|
| 97 |
-
config_path = os.path.join(project_root, "configs/equiformer_v2.yaml")
|
| 98 |
-
model, model_config = get_model(config_path)
|
| 99 |
-
|
| 100 |
-
checkpoint_path = os.path.join(project_root, "ckpt/eqv2.ckpt")
|
| 101 |
-
state_dict = torch.load(checkpoint_path, weights_only=True)["state_dict"]
|
| 102 |
-
state_dict = {k.replace("potential.", ""): v for k, v in state_dict.items()}
|
| 103 |
-
model.load_state_dict(state_dict, strict=False)
|
| 104 |
-
|
| 105 |
-
model.eval()
|
| 106 |
-
model.to("cuda")
|
| 107 |
-
|
| 108 |
-
# Example 1: load a dataset file and predict the first batch
|
| 109 |
-
from ocpmodels.ff_lmdb import LmdbDataset
|
| 110 |
-
|
| 111 |
-
dataset_path = os.path.join(project_root, "data/sample_100.lmdb")
|
| 112 |
-
dataset = LmdbDataset(dataset_path)
|
| 113 |
-
# either use the dataset directly or use a dataloader
|
| 114 |
-
batch = dataset[0]
|
| 115 |
-
for k, v in batch.items():
|
| 116 |
-
print(k, v.shape)
|
| 117 |
-
batch = Batch.from_data_list([batch])
|
| 118 |
-
# dataloader = TGDataLoader(dataset, batch_size=1, shuffle=False)
|
| 119 |
-
# batch = next(iter(dataloader))
|
| 120 |
-
energy, forces, eigenpred = predict(batch, model)
|
| 121 |
-
print("\nExample 1:")
|
| 122 |
-
print(f" Energy: {energy.shape}")
|
| 123 |
-
print(f" Forces: {forces.shape}")
|
| 124 |
-
print(f" Eigenpred: {eigenpred.keys()}")
|
| 125 |
-
|
| 126 |
-
# Example 2: create a random data object with random positions and predict
|
| 127 |
-
n_atoms = 10
|
| 128 |
-
elements = torch.tensor([1, 6, 7, 8]) # H, C, N, O
|
| 129 |
-
data = TGData(
|
| 130 |
-
pos=torch.randn(n_atoms, 3),
|
| 131 |
-
z=elements[torch.randint(0, 4, (n_atoms,))],
|
| 132 |
-
natoms=n_atoms,
|
| 133 |
-
)
|
| 134 |
-
data = Batch.from_data_list([data])
|
| 135 |
-
|
| 136 |
-
energy, forces, eigenpred = predict(data, model)
|
| 137 |
-
print("\nExample 2:")
|
| 138 |
-
print(f" Energy: {energy.shape}")
|
| 139 |
-
print(f" Forces: {forces.shape}")
|
| 140 |
-
print(f" Eigenpred: {eigenpred.keys()}")
|
| 141 |
-
|
| 142 |
-
# Example 3: predict gad
|
| 143 |
-
gad = predict_gad(data, model)
|
| 144 |
-
print("\nExample 3:")
|
| 145 |
-
print(f" GAD: {gad.shape}")
|
| 146 |
-
|
| 147 |
-
# Example 4: predict gad with hessian
|
| 148 |
-
gad = predict_gad_with_hessian(data, model)
|
| 149 |
-
print(f" GAD with Hessian: {gad.shape}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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