File size: 17,281 Bytes
ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 b470349 ce9b7f3 | 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 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 | import os
import sys
ROOT = os.path.dirname(os.path.abspath(__file__)) # path to experiments/
ROOT = os.path.abspath(os.path.join(ROOT, ".")) # repo root
sys.path.insert(0, ROOT) # so local packages import
sys.path.insert(0, os.path.join(ROOT, "equiformer_v2/ocp")) # so 'ocpmodels' resolves
import argparse
from datetime import datetime
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.utils.data import DataLoader, DistributedSampler
from torch.optim.lr_scheduler import CosineAnnealingLR, LambdaLR
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from pytorch_lightning import seed_everything
from tqdm import tqdm
from datetime import datetime
from equiformer_v2.nets.equiformer_v2.equiformer_v2_oc20 import EquiformerV2_OC20 as EquiformerV2
from utils import *
from model_configs import *
from types import SimpleNamespace
import wandb
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--name",
type=str,
default="default",
help="Optional experiment name prefix (used in checkpoint path and logging)."
)
# New: experiment controls
parser.add_argument(
"--model_config",
type=str,
choices=["orig", "small"],
default="orig",
help="Choose Equiformer model config preset."
)
parser.add_argument(
"--seed",
type=int,
default=42,
help="Random seed."
)
parser.add_argument(
"--dataset",
type=str,
required=True,
help="Path to the training/validation .h5 dataset.",
)
#-------------------------------------
args, _ = parser.parse_known_args()
# DDP
local_rank = int(os.environ.get("LOCAL_RANK", 0))
torch.cuda.set_device(local_rank)
dist.init_process_group(backend="nccl", init_method="env://")
device = torch.device(f'cuda:{local_rank}' if torch.cuda.is_available() else "cpu")
# hyperparams:
num_epochs = 100
lr = 0.0004
weight_decay = 1e-3
loss_forces_weight = 25
batch_size = 1
eval_batch_size = 1
# NOTE idk why
SEED = args.seed
DATA_PATH = args.dataset
#TEST_DATA_PATH = args.test_data_path
if args.model_config == "orig":
model_config = model_config_orig
model_config = {**model_config, "avg_num_nodes": 86.7569, "avg_degree": 18.64958191066762} # avg_num_nodes is NOT used and is given here for the sake of completeness
else:
model_config = model_config_small
# NOTE They will change I'm pretty sure later
model_config = {**model_config, "avg_num_nodes": 86.7569, "avg_degree": 18.64958191066762} # avg_num_nodes is NOT used and is given here for the sake of completeness
seed_everything(SEED, workers=True)
# NOTE Needed?
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
train_dataset = DFTDatasetH5(DATA_PATH, split="train")#, verify_splits=True)
val_dataset = DFTDatasetH5(DATA_PATH, split="val")#, verify_splits=True)
#test_dataset = DFTDatasetH5(TEST_DATA_PATH)
# create DistributedSampler for each dataset:
train_sampler = DistributedSampler(train_dataset, shuffle=True)
val_sampler = DistributedSampler(val_dataset)
#test_sampler = DistributedSampler(test_dataset)
# adjust the DataLoaders:
train_loader = DataLoader(train_dataset, batch_size, sampler=train_sampler, shuffle=False, collate_fn=custom_collate_fn)
val_loader = DataLoader(val_dataset, eval_batch_size, sampler=val_sampler, shuffle=False, collate_fn=custom_collate_fn)
#test_loader = DataLoader(test_dataset, eval_batch_size, sampler=test_sampler, shuffle=False, collate_fn=custom_collate_fn)
model = EquiformerV2(None, None, None, **model_config).to(device)
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
CHECKPOINT_PATH = (
f"checkpoints/equiformer/"
f"{datetime.now().strftime('%y%m%d_%H%M%S')}_"
f"{args.name}_"
f"{args.model_config}_"
f"{args.dataset}_"
f"seed{SEED}"
)
# Set up Wandb
run = None
if dist.get_rank() == 0:
run = wandb.init(
project="equimodel-mxene", # change
name=os.path.basename(CHECKPOINT_PATH), # nice readable run name
config={
"seed": SEED,
"dataset": args.dataset,
"model_config": args.model_config,
"num_epochs": num_epochs,
"lr": lr,
"weight_decay": weight_decay,
"loss_forces_weight": loss_forces_weight,
"batch_size": batch_size,
"eval_batch_size": eval_batch_size,
"world_size": dist.get_world_size(),
},
)
# (Optional) make W&B charts nicer by telling it what the “step” axis is
wandb.define_metric("epoch")
wandb.define_metric("train/*", step_metric="epoch")
wandb.define_metric("val/*", step_metric="epoch")
wandb.define_metric("test/*", step_metric="epoch")
if dist.get_rank() == 0:
print("Running...\n")
print(f'Seed: {args.seed}')
print(f'Model config: {args.model_config}')
print(f'Dataset: {args.dataset}\n')
print(f"Dataset size:\ntrain: {len(train_dataset)}, val: {len(val_dataset)}, test: {len([])}")
count_parameters(model)
print(f'Checkpoint path: {CHECKPOINT_PATH}')
os.makedirs(CHECKPOINT_PATH, exist_ok=True)
#dist.barrier()
best_val_metric = float('inf') # for tracking the best validation loss
criterion = nn.L1Loss(reduction="mean")
optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
scheduler = CosineAnnealingLR(optimizer, T_max=num_epochs, eta_min=0.01*lr)
# train and validate the model:
train_ls, train_ls_f, train_ls_e, val_ls, val_ls_f, val_ls_e = \
train_and_validate(
model,
train_loader,
val_loader,
criterion,
optimizer,
device,
loss_forces_weight=loss_forces_weight,
num_epochs=num_epochs,
scheduler=scheduler,
best_val_metric=best_val_metric,
checkpoint_path=CHECKPOINT_PATH)
# if args.do_test:
# # load the best model:
# model, optimizer, epoch, best_val_metric = load_checkpoint(CHECKPOINT_PATH+"/best_model.pth", model, optimizer)
# if dist.get_rank() == 0:
# print(f"Model successfully loaded. Best val metric: {best_val_metric}")
# # sanity check: test on the validation set again
# if dist.get_rank() == 0:
# print(f"\nSanity check: testing on the validation set")
# _val_ls, _val_ls_forces, _val_ls_energy = test(model, val_loader, criterion, device)
# # test the model:
# test_ls, test_ls_forces, test_ls_energy = test(model, test_loader, criterion, device)
# if dist.get_rank() == 0:
# wandb.finish()
# dist.destroy_process_group()
def train_and_validate(model, train_loader, val_loader, criterion, optimizer, device,
num_epochs=10, loss_forces_weight=10, scheduler=None,
best_val_metric=float('inf'), checkpoint_path=''):
if dist.get_rank() == 0:
print("\n\nTraining the model")
train_ls, train_ls_f, train_ls_e, val_ls, val_ls_f, val_ls_e = [], [], [], [], [], []
t0 = datetime.now()
# global step for per-batch logging if you want it later
global_step = 0
for epoch in range(num_epochs):
train_loader.sampler.set_epoch(epoch)
model.train()
train_loss_optim_num = 0.0
train_loss_forces = 0.0
train_loss_energy = 0.0
total_atoms = 0
total_batch_systems = 0
# tqdm for training loop (only on main process)
train_iter = train_loader
if dist.get_rank() == 0:
train_iter = tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs} [Train]", leave=False)
for data in train_iter:
data = {k: v.to(device) for k, v in data.items()}
data = SimpleNamespace(**data)
optimizer.zero_grad()
eff_batch_size = data.natoms.sum().item()
batch_systems = data.natoms.shape[0]
total_atoms += eff_batch_size
total_batch_systems += batch_systems
pred_energy, pred_forces = model(data)
loss_forces = criterion(pred_forces, data.forces)
loss_energy = criterion(pred_energy, data.energy)
loss = loss_forces_weight * loss_forces + (1 / eff_batch_size) * loss_energy
# NOTE Logging what we actually optimize as well
train_loss_optim_num += loss.item() * eff_batch_size
# train_loss_optim_num += (
# loss_forces_weight * loss_forces.item() * eff_batch_size
# + loss_energy.item()
# )
loss.backward()
optimizer.step()
train_loss_forces += loss_forces.item() * eff_batch_size
train_loss_energy += loss_energy.item() * batch_systems
if dist.get_rank() == 0:
train_iter.set_postfix({
"forces_loss": f"{loss_forces.item():.4f}",
"energy_loss": f"{loss_energy.item():.4f}"
})
global_step += 1
if scheduler is not None:
scheduler.step()
torch.cuda.synchronize()
torch.cuda.empty_cache()
train_loss_tensor = torch.tensor([train_loss_forces, train_loss_energy, train_loss_optim_num,
total_atoms, total_batch_systems], device=device) # NOTE removed train_loss from index 0
dist.all_reduce(train_loss_tensor, op=dist.ReduceOp.SUM)
train_force_num, train_energy_num, train_optim_num, train_atoms_den, train_systems_den = train_loss_tensor.tolist()
train_loss_forces = train_force_num / train_atoms_den
train_loss_energy = train_energy_num / train_systems_den
train_loss = train_loss_forces + train_loss_energy
train_loss_optim = train_optim_num / train_atoms_den
# NOTE Skipping the indexing
#train_loss_forces = train_loss_tensor[0].item() / train_loss_tensor[2].item()
#train_loss_energy = train_loss_tensor[1].item() / train_loss_tensor[3].item()
#train_loss = train_loss_forces + train_loss_energy
# validation phase:
model.eval()
val_loss_optim_num = 0.0
val_loss_forces = 0.0
val_loss_energy = 0.0
total_val_atoms = 0
total_val_batch_systems = 0
val_iter = val_loader
if dist.get_rank() == 0:
val_iter = tqdm(val_loader, desc=f"Epoch {epoch+1}/{num_epochs} [Val]", leave=False)
with torch.no_grad():
for data in val_iter:
data = {k: v.to(device) for k, v in data.items()}
data = SimpleNamespace(**data)
eff_batch_size = data.natoms.sum().item()
batch_systems = data.natoms.shape[0]
total_val_atoms += eff_batch_size
total_val_batch_systems += batch_systems
pred_energy, pred_forces = model(data)
loss_forces = criterion(pred_forces, data.forces)
loss_energy = criterion(pred_energy, data.energy)
loss = loss_forces + loss_energy
# NOTE Logging what we actually optimize as well
loss_optim = loss_forces_weight * loss_forces + (1.0 / eff_batch_size) * loss_energy
val_loss_optim_num += loss_optim.item() * eff_batch_size
val_loss_forces += loss_forces.item() * eff_batch_size
val_loss_energy += loss_energy.item() * batch_systems
if dist.get_rank() == 0:
val_iter.set_postfix({
"forces_loss": f"{loss_forces.item():.4f}",
"energy_loss": f"{loss_energy.item():.4f}"
})
val_loss_tensor = torch.tensor([val_loss_forces, val_loss_energy, val_loss_optim_num,
total_val_atoms, total_val_batch_systems], device=device)
dist.all_reduce(val_loss_tensor, op=dist.ReduceOp.SUM)
val_force_num, val_energy_num, val_optim_num, val_atoms_den, val_systems_den = val_loss_tensor.tolist()
val_loss_forces = val_force_num / val_atoms_den
val_loss_energy = val_energy_num / val_systems_den
val_loss = val_loss_forces + val_loss_energy
val_loss_optim = val_optim_num / val_atoms_den
#val_loss_forces = val_loss_tensor[1].item() / val_loss_tensor[-2].item()
#val_loss_energy = val_loss_tensor[2].item() / val_loss_tensor[-1].item()
#val_loss = val_loss_forces + val_loss_energy
# collect losses
train_ls.append(train_loss)
train_ls_f.append(train_loss_forces)
train_ls_e.append(train_loss_energy)
val_ls.append(val_loss)
val_ls_f.append(val_loss_forces)
val_ls_e.append(val_loss_energy)
if dist.get_rank() == 0:
wandb.log(
{
"epoch": epoch + 1,
"train/loss_forces": train_loss_forces,
"train/loss_energy": train_loss_energy,
"train/loss_total": train_loss,
"train/loss_optim": train_loss_optim,
"val/loss_forces": val_loss_forces,
"val/loss_energy": val_loss_energy,
"val/loss_total": val_loss,
"val/loss_optim": val_loss_optim,
"lr": optimizer.param_groups[0]["lr"],
},
step=epoch + 1, # epoch-step
)
if val_loss < best_val_metric:
best_val_metric = val_loss
save_checkpoint(model, optimizer, epoch, best_val_metric, checkpoint_path, is_best=True)
print(f"Epoch {epoch+1}: New best model saved with validation loss {val_loss:.4f}")
if epoch == num_epochs - 1:
save_checkpoint(model, optimizer, epoch, val_loss, checkpoint_path, is_best=False)
print(f"Epoch {epoch+1}: Model saved with validation loss {val_loss:.4f}")
t1 = datetime.now()
print(f"Epoch {epoch+1} ({t1 - t0}): "
f"Train Loss: {train_loss_forces:.4f} + {train_loss_energy:.4f} = {train_loss:.4f}, "
f"Validation Loss: {val_loss_forces:.4f} + {val_loss_energy:.4f} = {val_loss:.4f}")
print("Training and validation done")
return train_ls, train_ls_f, train_ls_e, val_ls, val_ls_f, val_ls_e
def test(model, test_loader, criterion, device):
if dist.get_rank() == 0:
print("\n\nTesting the model")
model.eval()
test_loss = torch.tensor(0.0, device=device)
test_loss_forces = torch.tensor(0.0, device=device)
test_loss_energy = torch.tensor(0.0, device=device)
total_test_atoms = torch.tensor(0, device=device)
total_test_batch_systems = torch.tensor(0, device=device)
with torch.no_grad():
for data in test_loader:
data = {k: v.to(device) for k, v in data.items()}
data = SimpleNamespace(**data)
pred_energy, pred_forces= model(data)
loss_forces = criterion(pred_forces, data.forces)
loss_energy = criterion(pred_energy, data.energy)
loss = loss_forces + loss_energy
eff_batch_size = data.natoms.sum().item()
batch_systems = data.natoms.shape[0]
total_test_atoms += eff_batch_size
total_test_batch_systems += batch_systems
test_loss_forces += loss_forces * eff_batch_size
test_loss_energy += loss_energy * batch_systems
dist.all_reduce(test_loss_forces, op=dist.ReduceOp.SUM)
dist.all_reduce(test_loss_energy, op=dist.ReduceOp.SUM)
dist.all_reduce(total_test_atoms, op=dist.ReduceOp.SUM)
dist.all_reduce(total_test_batch_systems, op=dist.ReduceOp.SUM)
test_loss_forces = test_loss_forces.item() / total_test_atoms.item()
test_loss_energy = test_loss_energy.item() / total_test_batch_systems.item()
test_loss = test_loss_forces + test_loss_energy
if dist.get_rank() == 0:
# NOTE Perhaps we can skip logging in test
# wandb.log(
# {
# "epoch": num_epochs, # or epoch+1 if you pass it in
# "test/loss_forces": test_loss_forces,
# "test/loss_energy": test_loss_energy,
# "test/loss_total": test_loss,
# },
# step=num_epochs,
# )
print(f'Test Loss: {test_loss_forces:.4f} + {test_loss_energy:.4f} = {test_loss:.4f}')
return test_loss, test_loss_forces, test_loss_energy
else:
return None, None, None
if __name__ == "__main__":
main() |