anonymous commited on
Commit ·
0301639
1
Parent(s): a1225ae
Added scripts for matris, updated readme
Browse files- README.md +15 -2
- datasets/xyz/{testdata.xyz → test.xyz} +0 -0
- models/matris/README.md +0 -5
- models/matris/run_matris.py +254 -165
- models/matris/run_matris_ddp.py +0 -541
- models/matris/scripts/bench_matris_speed_single.sh +74 -0
- models/matris/scripts/eval_matris.sh +103 -0
- models/matris/scripts/run_matris.sh +108 -0
README.md
CHANGED
|
@@ -10,6 +10,19 @@ size_categories:
|
|
| 10 |
- 10K<n<100K
|
| 11 |
---
|
| 12 |
|
| 13 |
-
# Introduction
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
- 10K<n<100K
|
| 11 |
---
|
| 12 |
|
|
|
|
| 13 |
|
| 14 |
+
|
| 15 |
+
## Repository Structure
|
| 16 |
+
|
| 17 |
+
Datasets are stored in the `datasets/` directory and are provided in both `.h5` and `.xyz` formats.
|
| 18 |
+
|
| 19 |
+
All model implementations, training code, evaluation code, and checkpoints are located in the `models/` directory. Each model subdirectory contains:
|
| 20 |
+
|
| 21 |
+
- `runs/` — stores trained model checkpoints and experiment outputs.
|
| 22 |
+
- `scripts/` — contains training, evaluation, and benchmarking shell scripts.
|
| 23 |
+
|
| 24 |
+
The scripts are configured to be launched from the repository root directory. For example, to start training of a new matris model, run
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
./models/matris/scripts/run_matris.sh
|
| 28 |
+
|
datasets/xyz/{testdata.xyz → test.xyz}
RENAMED
|
File without changes
|
models/matris/README.md
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
# Introduction
|
| 2 |
-
|
| 3 |
-
To train matris, run the run_matris.py script, there's also a ddp version called run_matris_ddp.py
|
| 4 |
-
|
| 5 |
-
To eval matris, run the eval_matris.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models/matris/run_matris.py
CHANGED
|
@@ -1,38 +1,36 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
| 3 |
import collections
|
|
|
|
| 4 |
import random
|
|
|
|
| 5 |
from pathlib import Path
|
| 6 |
|
| 7 |
import numpy as np
|
| 8 |
import torch
|
|
|
|
| 9 |
from torch import nn
|
|
|
|
| 10 |
from torch.utils.data import DataLoader
|
|
|
|
|
|
|
| 11 |
import wandb
|
| 12 |
|
| 13 |
from matris.model.model import MatRIS
|
| 14 |
from matris.model.reference_energy import AtomRef
|
| 15 |
from matris_dataset import MatRISDataset, matris_collate_fn, move_matris_batch_to_device
|
| 16 |
-
import argparse
|
| 17 |
-
from datetime import datetime
|
| 18 |
-
from tqdm import tqdm
|
| 19 |
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
# =========================
|
| 24 |
-
REPO_ROOT = Path(__file__).resolve().parents[2]
|
| 25 |
-
|
| 26 |
-
TRAIN_PATH = str(REPO_ROOT / "datasets/xyz/train.xyz")
|
| 27 |
-
VAL_PATH = str(REPO_ROOT / "datasets/xyz/val.xyz")
|
| 28 |
-
SAVE_DIR = REPO_ROOT / "models/matris/checkpoints_matris"
|
| 29 |
|
| 30 |
PROJECT_NAME = "matris-minimal-training"
|
| 31 |
-
RUN_NAME = "matris-ef"
|
| 32 |
|
| 33 |
BATCH_SIZE = 1
|
| 34 |
NUM_WORKERS = 0
|
| 35 |
-
EPOCHS =
|
| 36 |
LR = 3e-4
|
| 37 |
MIN_LR = 3e-6
|
| 38 |
WEIGHT_DECAY = 1e-2
|
|
@@ -41,30 +39,57 @@ SEED = 42
|
|
| 41 |
ENERGY_LOSS_WEIGHT = 1.0
|
| 42 |
FORCE_LOSS_WEIGHT = 1.0
|
| 43 |
|
| 44 |
-
|
| 45 |
SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
| 46 |
|
| 47 |
-
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 48 |
-
|
| 49 |
E0S_DEFAULT = {
|
| 50 |
-
1: 2.467478445,
|
| 51 |
-
6: 8.0273263225,
|
| 52 |
-
8: 3.334308855,
|
| 53 |
-
22: 4.879036065,
|
| 54 |
}
|
| 55 |
|
| 56 |
-
# NOTE Make sure pretrained changes weights (the model size changes, so that's enough of an gurantee)
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
def set_seed(seed: int) -> None:
|
|
|
|
|
|
|
|
|
|
| 62 |
random.seed(seed)
|
| 63 |
np.random.seed(seed)
|
| 64 |
torch.manual_seed(seed)
|
| 65 |
torch.cuda.manual_seed_all(seed)
|
| 66 |
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
def build_reference_energy_module(model: MatRIS, e0_dict: dict[int, float]) -> AtomRef:
|
| 69 |
atom_ref = AtomRef(reference_energy="mptrj", is_intensive=model.is_intensive)
|
| 70 |
|
|
@@ -83,8 +108,6 @@ def build_reference_energy_module(model: MatRIS, e0_dict: dict[int, float]) -> A
|
|
| 83 |
return atom_ref
|
| 84 |
|
| 85 |
|
| 86 |
-
|
| 87 |
-
# WHat Matris paper is doing
|
| 88 |
class WeightedEnergyForcesMAELoss(nn.Module):
|
| 89 |
def __init__(self, energy_weight: float = 1.0, forces_weight: float = 1.0):
|
| 90 |
super().__init__()
|
|
@@ -98,9 +121,8 @@ class WeightedEnergyForcesMAELoss(nn.Module):
|
|
| 98 |
out: dict,
|
| 99 |
do_eval: bool = False,
|
| 100 |
):
|
| 101 |
-
n_atoms = out["atoms_per_graph"].float()
|
| 102 |
-
|
| 103 |
-
# NOTE out["e"] is eV/atom if model.is_intensive=True (which it is), else eV total NOTE
|
| 104 |
if model.is_intensive:
|
| 105 |
pred_energy_per_atom = out["e"]
|
| 106 |
pred_total_energy = out["e"] * n_atoms
|
|
@@ -108,25 +130,18 @@ class WeightedEnergyForcesMAELoss(nn.Module):
|
|
| 108 |
pred_total_energy = out["e"]
|
| 109 |
pred_energy_per_atom = pred_total_energy / n_atoms
|
| 110 |
|
| 111 |
-
ref_total_energy = batch["energy"]
|
| 112 |
ref_energy_per_atom = ref_total_energy / n_atoms
|
| 113 |
|
| 114 |
force_losses = []
|
| 115 |
for pred_f, ref_f in zip(out["f"], batch["forces"]):
|
| 116 |
-
# one scalar per graph: mean over atoms and xyz components
|
| 117 |
force_losses.append(torch.abs(pred_f - ref_f).mean())
|
| 118 |
|
| 119 |
loss_forces = torch.stack(force_losses).mean()
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
))
|
| 125 |
-
|
| 126 |
-
# Per system
|
| 127 |
-
# per_system_error = torch.abs(pred_total_energy - ref_total_energy)
|
| 128 |
-
# loss_energy = torch.sum(per_system_error * n_atoms) / torch.sum(n_atoms)
|
| 129 |
-
|
| 130 |
|
| 131 |
total_loss = (
|
| 132 |
self.forces_weight * loss_forces
|
|
@@ -135,14 +150,15 @@ class WeightedEnergyForcesMAELoss(nn.Module):
|
|
| 135 |
|
| 136 |
return (
|
| 137 |
total_loss,
|
| 138 |
-
loss_energy,
|
| 139 |
-
loss_forces,
|
| 140 |
pred_total_energy,
|
| 141 |
ref_total_energy,
|
| 142 |
)
|
| 143 |
|
|
|
|
| 144 |
def run_epoch(
|
| 145 |
-
model:
|
| 146 |
loader: DataLoader,
|
| 147 |
optimizer: torch.optim.Optimizer | None,
|
| 148 |
scheduler: torch.optim.lr_scheduler._LRScheduler | None,
|
|
@@ -154,6 +170,8 @@ def run_epoch(
|
|
| 154 |
is_train = optimizer is not None
|
| 155 |
model.train(is_train)
|
| 156 |
|
|
|
|
|
|
|
| 157 |
running = {
|
| 158 |
"loss": 0.0,
|
| 159 |
"energy_mae_per_atom": 0.0,
|
|
@@ -163,21 +181,30 @@ def run_epoch(
|
|
| 163 |
"ref_energy_mean": 0.0,
|
| 164 |
"lr": 0.0,
|
| 165 |
}
|
| 166 |
-
|
| 167 |
|
| 168 |
n_batches = 0
|
| 169 |
|
| 170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
batch = move_matris_batch_to_device(batch, device=device)
|
| 173 |
|
| 174 |
if is_train:
|
| 175 |
-
optimizer.zero_grad()
|
| 176 |
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
loss, energy_loss, force_loss, pred_total_energy, target_total_energy = criterion(
|
| 180 |
-
model=
|
| 181 |
batch=batch,
|
| 182 |
out=out,
|
| 183 |
do_eval=False,
|
|
@@ -187,11 +214,6 @@ def run_epoch(
|
|
| 187 |
loss.backward()
|
| 188 |
optimizer.step()
|
| 189 |
|
| 190 |
-
# For logging: force MAE per atom/component over full batch
|
| 191 |
-
#pred_forces = torch.cat(out["f"], dim=0)
|
| 192 |
-
#ref_forces = torch.cat(batch["forces"], dim=0)
|
| 193 |
-
#force_mae_per_component = torch.abs(pred_forces - ref_forces).mean()
|
| 194 |
-
|
| 195 |
current_lr = optimizer.param_groups[0]["lr"] if is_train else 0.0
|
| 196 |
|
| 197 |
running["loss"] += loss.detach().item()
|
|
@@ -199,26 +221,40 @@ def run_epoch(
|
|
| 199 |
running["force_mae_per_component"] += force_loss.detach().item()
|
| 200 |
running["pred_total_energy_mean"] += pred_total_energy.detach().mean().item()
|
| 201 |
running["target_total_energy_mean"] += target_total_energy.detach().mean().item()
|
| 202 |
-
running["ref_energy_mean"] += out["ref_energy"].detach().mean().item()
|
| 203 |
-
running["lr"] += current_lr
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
n_batches += 1
|
| 206 |
|
|
|
|
|
|
|
| 207 |
if n_batches == 0:
|
| 208 |
-
raise RuntimeError(f"No batches found in {split} loader.")
|
| 209 |
|
| 210 |
metrics = {k: v / n_batches for k, v in running.items()}
|
| 211 |
metrics["epoch"] = epoch
|
| 212 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
if is_train and scheduler is not None:
|
| 214 |
scheduler.step()
|
| 215 |
|
| 216 |
-
|
|
|
|
| 217 |
|
| 218 |
return metrics
|
| 219 |
|
|
|
|
| 220 |
def parse_args():
|
| 221 |
-
parser = argparse.ArgumentParser(description="Train MatRIS on energy/force data.")
|
| 222 |
|
| 223 |
parser.add_argument("--train_path", type=str, default=TRAIN_PATH)
|
| 224 |
parser.add_argument("--val_path", type=str, default=VAL_PATH)
|
|
@@ -239,13 +275,11 @@ def parse_args():
|
|
| 239 |
|
| 240 |
parser.add_argument("--seed", type=int, default=SEED)
|
| 241 |
parser.add_argument("--save_dir", type=str, default=str(SAVE_DIR))
|
| 242 |
-
parser.add_argument("--device", type=str, default=DEVICE)
|
| 243 |
|
| 244 |
parser.add_argument(
|
| 245 |
"--is_conservative",
|
| 246 |
action=argparse.BooleanOptionalAction,
|
| 247 |
default=True,
|
| 248 |
-
help="Use conservative forces: F = -dE/dx. Use --no-is_conservative for direct force head.",
|
| 249 |
)
|
| 250 |
|
| 251 |
parser.add_argument(
|
|
@@ -258,78 +292,121 @@ def parse_args():
|
|
| 258 |
"--model_name",
|
| 259 |
type=str,
|
| 260 |
default=None,
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
)
|
| 263 |
|
| 264 |
return parser.parse_args()
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
if __name__ == "__main__":
|
| 270 |
args = parse_args()
|
| 271 |
|
| 272 |
set_seed(args.seed)
|
| 273 |
|
| 274 |
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 275 |
-
|
| 276 |
run_dir = Path(args.save_dir) / f"{args.run_name}_{timestamp}"
|
| 277 |
-
run_dir.mkdir(parents=True, exist_ok=True)
|
| 278 |
-
|
| 279 |
-
print(f"Saving checkpoints to: {run_dir}")
|
| 280 |
-
|
| 281 |
-
wandb.init(
|
| 282 |
-
project=args.project_name,
|
| 283 |
-
name=args.run_name,
|
| 284 |
-
config=vars(args) | {
|
| 285 |
-
"scheduler": "CosineAnnealingLR",
|
| 286 |
-
"loss": "forces_mae + energy_mae_per_atom",
|
| 287 |
-
},
|
| 288 |
-
)
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
| 291 |
if args.model_name is None or args.model_name == "none":
|
| 292 |
-
|
| 293 |
-
|
|
|
|
| 294 |
else:
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
| 300 |
model.force_stress_head.is_conservation = args.is_conservative
|
| 301 |
|
| 302 |
-
|
| 303 |
if args.use_reference_energy:
|
| 304 |
-
model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT)
|
| 305 |
else:
|
| 306 |
model.reference_energy = None
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
-
#train_dataset = CachedMatRISDataset(args.train_path)
|
| 314 |
-
#val_dataset = CachedMatRISDataset(args.val_path)
|
| 315 |
-
|
| 316 |
train_loader = DataLoader(
|
| 317 |
train_dataset,
|
| 318 |
batch_size=args.batch_size,
|
| 319 |
-
|
|
|
|
| 320 |
num_workers=args.num_workers,
|
| 321 |
collate_fn=matris_collate_fn,
|
|
|
|
| 322 |
)
|
| 323 |
|
| 324 |
val_loader = DataLoader(
|
| 325 |
val_dataset,
|
| 326 |
batch_size=args.batch_size,
|
|
|
|
| 327 |
shuffle=False,
|
| 328 |
num_workers=args.num_workers,
|
| 329 |
collate_fn=matris_collate_fn,
|
|
|
|
| 330 |
)
|
| 331 |
|
| 332 |
-
|
| 333 |
optimizer = torch.optim.AdamW(
|
| 334 |
model.parameters(),
|
| 335 |
lr=args.lr,
|
|
@@ -347,24 +424,28 @@ if __name__ == "__main__":
|
|
| 347 |
forces_weight=args.force_weight,
|
| 348 |
)
|
| 349 |
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
print(f"Train size: {len(train_dataset)}")
|
| 355 |
-
print(f"Val size: {len(val_dataset)}")
|
| 356 |
|
| 357 |
-
best_checkpoints = []
|
| 358 |
MAX_BEST_CKPTS = 5
|
| 359 |
|
| 360 |
-
for epoch in tqdm(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
train_metrics = run_epoch(
|
| 362 |
model=model,
|
| 363 |
loader=train_loader,
|
| 364 |
optimizer=optimizer,
|
| 365 |
scheduler=scheduler,
|
| 366 |
criterion=criterion,
|
| 367 |
-
device=
|
| 368 |
epoch=epoch,
|
| 369 |
split="train",
|
| 370 |
)
|
|
@@ -375,79 +456,87 @@ if __name__ == "__main__":
|
|
| 375 |
optimizer=None,
|
| 376 |
scheduler=None,
|
| 377 |
criterion=criterion,
|
| 378 |
-
device=
|
| 379 |
epoch=epoch,
|
| 380 |
split="val",
|
| 381 |
)
|
| 382 |
|
| 383 |
current_lr = optimizer.param_groups[0]["lr"]
|
| 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 |
-
ckpt_path = run_dir / ckpt_name
|
| 420 |
-
|
| 421 |
-
should_save = False
|
| 422 |
-
|
| 423 |
-
if len(best_checkpoints) < MAX_BEST_CKPTS:
|
| 424 |
-
should_save = True
|
| 425 |
-
else:
|
| 426 |
-
worst_ckpt = max(best_checkpoints, key=lambda x: x["val_loss"])
|
| 427 |
|
| 428 |
-
|
| 429 |
-
if worst_ckpt["path"].exists():
|
| 430 |
-
worst_ckpt["path"].unlink()
|
| 431 |
|
| 432 |
-
|
|
|
|
|
|
|
| 433 |
should_save = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
|
| 446 |
-
|
| 447 |
|
| 448 |
-
|
| 449 |
|
| 450 |
-
|
| 451 |
-
|
| 452 |
|
| 453 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import argparse
|
| 4 |
import collections
|
| 5 |
+
import os
|
| 6 |
import random
|
| 7 |
+
from datetime import datetime
|
| 8 |
from pathlib import Path
|
| 9 |
|
| 10 |
import numpy as np
|
| 11 |
import torch
|
| 12 |
+
import torch.distributed as dist
|
| 13 |
from torch import nn
|
| 14 |
+
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 15 |
from torch.utils.data import DataLoader
|
| 16 |
+
from torch.utils.data.distributed import DistributedSampler
|
| 17 |
+
from tqdm import tqdm
|
| 18 |
import wandb
|
| 19 |
|
| 20 |
from matris.model.model import MatRIS
|
| 21 |
from matris.model.reference_energy import AtomRef
|
| 22 |
from matris_dataset import MatRISDataset, matris_collate_fn, move_matris_batch_to_device
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
|
| 25 |
+
TRAIN_PATH = "datasets/trainingset_251216_train.xyz"
|
| 26 |
+
VAL_PATH = "datasets/trainingset_251216_val.xyz"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
PROJECT_NAME = "matris-minimal-training"
|
| 29 |
+
RUN_NAME = "matris-ef-ddp"
|
| 30 |
|
| 31 |
BATCH_SIZE = 1
|
| 32 |
NUM_WORKERS = 0
|
| 33 |
+
EPOCHS = 1000
|
| 34 |
LR = 3e-4
|
| 35 |
MIN_LR = 3e-6
|
| 36 |
WEIGHT_DECAY = 1e-2
|
|
|
|
| 39 |
ENERGY_LOSS_WEIGHT = 1.0
|
| 40 |
FORCE_LOSS_WEIGHT = 1.0
|
| 41 |
|
| 42 |
+
SAVE_DIR = Path("checkpoints_matris")
|
| 43 |
SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
| 44 |
|
|
|
|
|
|
|
| 45 |
E0S_DEFAULT = {
|
| 46 |
+
1: 2.467478445,
|
| 47 |
+
6: 8.0273263225,
|
| 48 |
+
8: 3.334308855,
|
| 49 |
+
22: 4.879036065,
|
| 50 |
}
|
| 51 |
|
|
|
|
| 52 |
|
| 53 |
+
def setup_ddp():
|
| 54 |
+
dist.init_process_group(backend="nccl")
|
| 55 |
+
local_rank = int(os.environ["LOCAL_RANK"])
|
| 56 |
+
rank = int(os.environ["RANK"])
|
| 57 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 58 |
+
torch.cuda.set_device(local_rank)
|
| 59 |
+
device = f"cuda:{local_rank}"
|
| 60 |
+
return local_rank, rank, world_size, device
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def cleanup_ddp():
|
| 64 |
+
if dist.is_initialized():
|
| 65 |
+
dist.destroy_process_group()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def is_main_process():
|
| 69 |
+
return (not dist.is_initialized()) or dist.get_rank() == 0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def reduce_mean(value: float, device: str) -> float:
|
| 73 |
+
tensor = torch.tensor(value, device=device, dtype=torch.float32)
|
| 74 |
+
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
|
| 75 |
+
tensor /= dist.get_world_size()
|
| 76 |
+
return tensor.item()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
def set_seed(seed: int) -> None:
|
| 80 |
+
rank = dist.get_rank() if dist.is_initialized() else 0
|
| 81 |
+
seed = seed + rank
|
| 82 |
+
|
| 83 |
random.seed(seed)
|
| 84 |
np.random.seed(seed)
|
| 85 |
torch.manual_seed(seed)
|
| 86 |
torch.cuda.manual_seed_all(seed)
|
| 87 |
|
| 88 |
|
| 89 |
+
def unwrap_model(model):
|
| 90 |
+
return model.module if isinstance(model, DDP) else model
|
| 91 |
+
|
| 92 |
+
|
| 93 |
def build_reference_energy_module(model: MatRIS, e0_dict: dict[int, float]) -> AtomRef:
|
| 94 |
atom_ref = AtomRef(reference_energy="mptrj", is_intensive=model.is_intensive)
|
| 95 |
|
|
|
|
| 108 |
return atom_ref
|
| 109 |
|
| 110 |
|
|
|
|
|
|
|
| 111 |
class WeightedEnergyForcesMAELoss(nn.Module):
|
| 112 |
def __init__(self, energy_weight: float = 1.0, forces_weight: float = 1.0):
|
| 113 |
super().__init__()
|
|
|
|
| 121 |
out: dict,
|
| 122 |
do_eval: bool = False,
|
| 123 |
):
|
| 124 |
+
n_atoms = out["atoms_per_graph"].float()
|
| 125 |
+
|
|
|
|
| 126 |
if model.is_intensive:
|
| 127 |
pred_energy_per_atom = out["e"]
|
| 128 |
pred_total_energy = out["e"] * n_atoms
|
|
|
|
| 130 |
pred_total_energy = out["e"]
|
| 131 |
pred_energy_per_atom = pred_total_energy / n_atoms
|
| 132 |
|
| 133 |
+
ref_total_energy = batch["energy"]
|
| 134 |
ref_energy_per_atom = ref_total_energy / n_atoms
|
| 135 |
|
| 136 |
force_losses = []
|
| 137 |
for pred_f, ref_f in zip(out["f"], batch["forces"]):
|
|
|
|
| 138 |
force_losses.append(torch.abs(pred_f - ref_f).mean())
|
| 139 |
|
| 140 |
loss_forces = torch.stack(force_losses).mean()
|
| 141 |
|
| 142 |
+
loss_energy = torch.mean(
|
| 143 |
+
torch.abs(pred_energy_per_atom - ref_energy_per_atom)
|
| 144 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
total_loss = (
|
| 147 |
self.forces_weight * loss_forces
|
|
|
|
| 150 |
|
| 151 |
return (
|
| 152 |
total_loss,
|
| 153 |
+
loss_energy,
|
| 154 |
+
loss_forces,
|
| 155 |
pred_total_energy,
|
| 156 |
ref_total_energy,
|
| 157 |
)
|
| 158 |
|
| 159 |
+
|
| 160 |
def run_epoch(
|
| 161 |
+
model: DDP,
|
| 162 |
loader: DataLoader,
|
| 163 |
optimizer: torch.optim.Optimizer | None,
|
| 164 |
scheduler: torch.optim.lr_scheduler._LRScheduler | None,
|
|
|
|
| 170 |
is_train = optimizer is not None
|
| 171 |
model.train(is_train)
|
| 172 |
|
| 173 |
+
raw_model = unwrap_model(model)
|
| 174 |
+
|
| 175 |
running = {
|
| 176 |
"loss": 0.0,
|
| 177 |
"energy_mae_per_atom": 0.0,
|
|
|
|
| 181 |
"ref_energy_mean": 0.0,
|
| 182 |
"lr": 0.0,
|
| 183 |
}
|
|
|
|
| 184 |
|
| 185 |
n_batches = 0
|
| 186 |
|
| 187 |
+
iterator = tqdm(loader, desc=f"Running {split}", disable=not is_main_process())
|
| 188 |
+
|
| 189 |
+
for batch in iterator:
|
| 190 |
+
if batch is None:
|
| 191 |
+
continue
|
| 192 |
|
| 193 |
batch = move_matris_batch_to_device(batch, device=device)
|
| 194 |
|
| 195 |
if is_train:
|
| 196 |
+
optimizer.zero_grad(set_to_none=True)
|
| 197 |
|
| 198 |
+
# Conservative forces need gradients even during validation.
|
| 199 |
+
if is_train or raw_model.force_stress_head.is_conservation:
|
| 200 |
+
with torch.enable_grad():
|
| 201 |
+
out = model(batch["graphs"], task="ef", is_training=is_train)
|
| 202 |
+
else:
|
| 203 |
+
with torch.no_grad():
|
| 204 |
+
out = model(batch["graphs"], task="ef", is_training=False)
|
| 205 |
|
| 206 |
loss, energy_loss, force_loss, pred_total_energy, target_total_energy = criterion(
|
| 207 |
+
model=raw_model,
|
| 208 |
batch=batch,
|
| 209 |
out=out,
|
| 210 |
do_eval=False,
|
|
|
|
| 214 |
loss.backward()
|
| 215 |
optimizer.step()
|
| 216 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
current_lr = optimizer.param_groups[0]["lr"] if is_train else 0.0
|
| 218 |
|
| 219 |
running["loss"] += loss.detach().item()
|
|
|
|
| 221 |
running["force_mae_per_component"] += force_loss.detach().item()
|
| 222 |
running["pred_total_energy_mean"] += pred_total_energy.detach().mean().item()
|
| 223 |
running["target_total_energy_mean"] += target_total_energy.detach().mean().item()
|
|
|
|
|
|
|
| 224 |
|
| 225 |
+
ref_energy = out["ref_energy"]
|
| 226 |
+
if torch.is_tensor(ref_energy):
|
| 227 |
+
running["ref_energy_mean"] += ref_energy.detach().mean().item()
|
| 228 |
+
else:
|
| 229 |
+
running["ref_energy_mean"] += float(ref_energy)
|
| 230 |
+
|
| 231 |
+
running["lr"] += current_lr
|
| 232 |
n_batches += 1
|
| 233 |
|
| 234 |
+
del out, loss, energy_loss, force_loss, pred_total_energy, target_total_energy
|
| 235 |
+
|
| 236 |
if n_batches == 0:
|
| 237 |
+
raise RuntimeError(f"No batches found in {split} loader on rank {dist.get_rank()}.")
|
| 238 |
|
| 239 |
metrics = {k: v / n_batches for k, v in running.items()}
|
| 240 |
metrics["epoch"] = epoch
|
| 241 |
|
| 242 |
+
# Average metrics across GPUs.
|
| 243 |
+
for k in list(metrics.keys()):
|
| 244 |
+
if k != "epoch":
|
| 245 |
+
metrics[k] = reduce_mean(metrics[k], device=device)
|
| 246 |
+
|
| 247 |
if is_train and scheduler is not None:
|
| 248 |
scheduler.step()
|
| 249 |
|
| 250 |
+
if is_main_process():
|
| 251 |
+
wandb.log({f"{split}/{k}": v for k, v in metrics.items()}, step=epoch)
|
| 252 |
|
| 253 |
return metrics
|
| 254 |
|
| 255 |
+
|
| 256 |
def parse_args():
|
| 257 |
+
parser = argparse.ArgumentParser(description="Train MatRIS on energy/force data with DDP.")
|
| 258 |
|
| 259 |
parser.add_argument("--train_path", type=str, default=TRAIN_PATH)
|
| 260 |
parser.add_argument("--val_path", type=str, default=VAL_PATH)
|
|
|
|
| 275 |
|
| 276 |
parser.add_argument("--seed", type=int, default=SEED)
|
| 277 |
parser.add_argument("--save_dir", type=str, default=str(SAVE_DIR))
|
|
|
|
| 278 |
|
| 279 |
parser.add_argument(
|
| 280 |
"--is_conservative",
|
| 281 |
action=argparse.BooleanOptionalAction,
|
| 282 |
default=True,
|
|
|
|
| 283 |
)
|
| 284 |
|
| 285 |
parser.add_argument(
|
|
|
|
| 292 |
"--model_name",
|
| 293 |
type=str,
|
| 294 |
default=None,
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--find_unused_parameters",
|
| 299 |
+
action=argparse.BooleanOptionalAction,
|
| 300 |
+
default=True,
|
| 301 |
+
help="Useful if some heads/branches are unused.",
|
| 302 |
)
|
| 303 |
|
| 304 |
return parser.parse_args()
|
| 305 |
|
| 306 |
+
|
| 307 |
+
def main():
|
| 308 |
+
local_rank, rank, world_size, device = setup_ddp()
|
|
|
|
| 309 |
args = parse_args()
|
| 310 |
|
| 311 |
set_seed(args.seed)
|
| 312 |
|
| 313 |
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
|
|
| 314 |
run_dir = Path(args.save_dir) / f"{args.run_name}_{timestamp}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 315 |
|
| 316 |
+
if is_main_process():
|
| 317 |
+
run_dir.mkdir(parents=True, exist_ok=True)
|
| 318 |
+
print(f"Saving checkpoints to: {run_dir}")
|
| 319 |
+
print(f"World size: {world_size}")
|
| 320 |
+
print(f"Per-GPU batch size: {args.batch_size}")
|
| 321 |
+
print(f"Effective batch size: {args.batch_size * world_size}")
|
| 322 |
+
|
| 323 |
+
wandb.init(
|
| 324 |
+
project=args.project_name,
|
| 325 |
+
name=args.run_name,
|
| 326 |
+
config=vars(args) | {
|
| 327 |
+
"scheduler": "CosineAnnealingLR",
|
| 328 |
+
"loss": "forces_mae + energy_mae_per_atom",
|
| 329 |
+
"world_size": world_size,
|
| 330 |
+
"effective_batch_size": args.batch_size * world_size,
|
| 331 |
+
},
|
| 332 |
+
)
|
| 333 |
|
| 334 |
if args.model_name is None or args.model_name == "none":
|
| 335 |
+
if is_main_process():
|
| 336 |
+
print("Training from scratch")
|
| 337 |
+
model = MatRIS(is_conservation=args.is_conservative)
|
| 338 |
else:
|
| 339 |
+
foundation_models_dir = os.environ.get("FOUNDATION_MODELS_DIR", "foundation_models")
|
| 340 |
+
if is_main_process():
|
| 341 |
+
print(f"Starting from foundation model: {args.model_name}")
|
| 342 |
+
model = MatRIS.load(
|
| 343 |
+
args.model_name,
|
| 344 |
+
device="cpu",
|
| 345 |
+
cache_dir=foundation_models_dir,
|
| 346 |
+
)
|
| 347 |
model.force_stress_head.is_conservation = args.is_conservative
|
| 348 |
|
|
|
|
| 349 |
if args.use_reference_energy:
|
| 350 |
+
model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT)
|
| 351 |
else:
|
| 352 |
model.reference_energy = None
|
| 353 |
|
| 354 |
+
model = model.to(device)
|
| 355 |
+
|
| 356 |
+
model = DDP(
|
| 357 |
+
model,
|
| 358 |
+
device_ids=[local_rank],
|
| 359 |
+
output_device=local_rank,
|
| 360 |
+
find_unused_parameters=args.find_unused_parameters,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
raw_model = unwrap_model(model)
|
| 364 |
+
|
| 365 |
+
if is_main_process():
|
| 366 |
+
print("Loaded config is_conservation:", raw_model.config.get("is_conservation"))
|
| 367 |
+
print("Actual force head is_conservation:", raw_model.force_stress_head.is_conservation)
|
| 368 |
+
print("Model is_intensive:", raw_model.is_intensive)
|
| 369 |
+
print(f"Using device: {device}")
|
| 370 |
+
|
| 371 |
+
train_dataset = MatRISDataset(args.train_path, model=raw_model)
|
| 372 |
+
val_dataset = MatRISDataset(args.val_path, model=raw_model)
|
| 373 |
+
|
| 374 |
+
train_sampler = DistributedSampler(
|
| 375 |
+
train_dataset,
|
| 376 |
+
num_replicas=world_size,
|
| 377 |
+
rank=rank,
|
| 378 |
+
shuffle=True,
|
| 379 |
+
drop_last=False,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
val_sampler = DistributedSampler(
|
| 383 |
+
val_dataset,
|
| 384 |
+
num_replicas=world_size,
|
| 385 |
+
rank=rank,
|
| 386 |
+
shuffle=False,
|
| 387 |
+
drop_last=False,
|
| 388 |
+
)
|
| 389 |
|
|
|
|
|
|
|
|
|
|
| 390 |
train_loader = DataLoader(
|
| 391 |
train_dataset,
|
| 392 |
batch_size=args.batch_size,
|
| 393 |
+
sampler=train_sampler,
|
| 394 |
+
shuffle=False,
|
| 395 |
num_workers=args.num_workers,
|
| 396 |
collate_fn=matris_collate_fn,
|
| 397 |
+
pin_memory=True,
|
| 398 |
)
|
| 399 |
|
| 400 |
val_loader = DataLoader(
|
| 401 |
val_dataset,
|
| 402 |
batch_size=args.batch_size,
|
| 403 |
+
sampler=val_sampler,
|
| 404 |
shuffle=False,
|
| 405 |
num_workers=args.num_workers,
|
| 406 |
collate_fn=matris_collate_fn,
|
| 407 |
+
pin_memory=True,
|
| 408 |
)
|
| 409 |
|
|
|
|
| 410 |
optimizer = torch.optim.AdamW(
|
| 411 |
model.parameters(),
|
| 412 |
lr=args.lr,
|
|
|
|
| 424 |
forces_weight=args.force_weight,
|
| 425 |
)
|
| 426 |
|
| 427 |
+
if is_main_process():
|
| 428 |
+
print(f"Conservative forces: {args.is_conservative}")
|
| 429 |
+
print(f"Train size: {len(train_dataset)}")
|
| 430 |
+
print(f"Val size: {len(val_dataset)}")
|
|
|
|
|
|
|
| 431 |
|
| 432 |
+
best_checkpoints = []
|
| 433 |
MAX_BEST_CKPTS = 5
|
| 434 |
|
| 435 |
+
for epoch in tqdm(
|
| 436 |
+
range(1, args.epochs + 1),
|
| 437 |
+
desc="Epoch",
|
| 438 |
+
disable=not is_main_process(),
|
| 439 |
+
):
|
| 440 |
+
train_sampler.set_epoch(epoch)
|
| 441 |
+
|
| 442 |
train_metrics = run_epoch(
|
| 443 |
model=model,
|
| 444 |
loader=train_loader,
|
| 445 |
optimizer=optimizer,
|
| 446 |
scheduler=scheduler,
|
| 447 |
criterion=criterion,
|
| 448 |
+
device=device,
|
| 449 |
epoch=epoch,
|
| 450 |
split="train",
|
| 451 |
)
|
|
|
|
| 456 |
optimizer=None,
|
| 457 |
scheduler=None,
|
| 458 |
criterion=criterion,
|
| 459 |
+
device=device,
|
| 460 |
epoch=epoch,
|
| 461 |
split="val",
|
| 462 |
)
|
| 463 |
|
| 464 |
current_lr = optimizer.param_groups[0]["lr"]
|
| 465 |
|
| 466 |
+
if is_main_process():
|
| 467 |
+
print(
|
| 468 |
+
f"Epoch {epoch:03d} | "
|
| 469 |
+
f"lr={current_lr:.2e} | "
|
| 470 |
+
f"train/loss={train_metrics['loss']:.6f} | "
|
| 471 |
+
f"train/e_per_atom={train_metrics['energy_mae_per_atom']:.6f} | "
|
| 472 |
+
f"train/f_per_component={train_metrics['force_mae_per_component']:.6f} | "
|
| 473 |
+
f"val/loss={val_metrics['loss']:.6f} | "
|
| 474 |
+
f"val/e_per_atom={val_metrics['energy_mae_per_atom']:.6f} | "
|
| 475 |
+
f"val/f_per_component={val_metrics['force_mae_per_component']:.6f}"
|
| 476 |
+
)
|
| 477 |
|
| 478 |
+
wandb.log({"epoch": epoch, "lr": current_lr}, step=epoch)
|
| 479 |
+
|
| 480 |
+
ckpt = {
|
| 481 |
+
"epoch": epoch,
|
| 482 |
+
"model_state_dict": raw_model.state_dict(),
|
| 483 |
+
"optimizer_state_dict": optimizer.state_dict(),
|
| 484 |
+
"scheduler_state_dict": scheduler.state_dict(),
|
| 485 |
+
"train_metrics": train_metrics,
|
| 486 |
+
"val_metrics": val_metrics,
|
| 487 |
+
"args": vars(args),
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
val_loss = val_metrics["loss"]
|
| 491 |
+
val_e = val_metrics["energy_mae_per_atom"]
|
| 492 |
+
val_f = val_metrics["force_mae_per_component"]
|
| 493 |
+
|
| 494 |
+
ckpt_name = (
|
| 495 |
+
f"best_epoch={epoch:04d}"
|
| 496 |
+
f"_val_loss={val_loss:.6f}"
|
| 497 |
+
f"_val_e_atom={val_e:.6f}"
|
| 498 |
+
f"_val_f_comp={val_f:.6f}.pt"
|
| 499 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
|
| 501 |
+
ckpt_path = run_dir / ckpt_name
|
|
|
|
|
|
|
| 502 |
|
| 503 |
+
should_save = False
|
| 504 |
+
|
| 505 |
+
if len(best_checkpoints) < MAX_BEST_CKPTS:
|
| 506 |
should_save = True
|
| 507 |
+
else:
|
| 508 |
+
worst_ckpt = max(best_checkpoints, key=lambda x: x["val_loss"])
|
| 509 |
+
if val_loss < worst_ckpt["val_loss"]:
|
| 510 |
+
if worst_ckpt["path"].exists():
|
| 511 |
+
worst_ckpt["path"].unlink()
|
| 512 |
+
best_checkpoints.remove(worst_ckpt)
|
| 513 |
+
should_save = True
|
| 514 |
|
| 515 |
+
if should_save:
|
| 516 |
+
torch.save(ckpt, ckpt_path)
|
| 517 |
|
| 518 |
+
best_checkpoints.append(
|
| 519 |
+
{
|
| 520 |
+
"path": ckpt_path,
|
| 521 |
+
"val_loss": val_loss,
|
| 522 |
+
"epoch": epoch,
|
| 523 |
+
}
|
| 524 |
+
)
|
| 525 |
|
| 526 |
+
best_checkpoints = sorted(best_checkpoints, key=lambda x: x["val_loss"])
|
| 527 |
|
| 528 |
+
print(f"Saved top-{MAX_BEST_CKPTS} checkpoint: {ckpt_name}")
|
| 529 |
|
| 530 |
+
wandb.run.summary["best_val_loss"] = best_checkpoints[0]["val_loss"]
|
| 531 |
+
wandb.run.summary["best_epoch"] = best_checkpoints[0]["epoch"]
|
| 532 |
|
| 533 |
+
dist.barrier()
|
| 534 |
+
|
| 535 |
+
if is_main_process():
|
| 536 |
+
wandb.finish()
|
| 537 |
+
|
| 538 |
+
cleanup_ddp()
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
if __name__ == "__main__":
|
| 542 |
+
main()
|
models/matris/run_matris_ddp.py
DELETED
|
@@ -1,541 +0,0 @@
|
|
| 1 |
-
from __future__ import annotations
|
| 2 |
-
|
| 3 |
-
import argparse
|
| 4 |
-
import collections
|
| 5 |
-
import os
|
| 6 |
-
import random
|
| 7 |
-
from datetime import datetime
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
|
| 10 |
-
import numpy as np
|
| 11 |
-
import torch
|
| 12 |
-
import torch.distributed as dist
|
| 13 |
-
from torch import nn
|
| 14 |
-
from torch.nn.parallel import DistributedDataParallel as DDP
|
| 15 |
-
from torch.utils.data import DataLoader
|
| 16 |
-
from torch.utils.data.distributed import DistributedSampler
|
| 17 |
-
from tqdm import tqdm
|
| 18 |
-
import wandb
|
| 19 |
-
|
| 20 |
-
from matris.model.model import MatRIS
|
| 21 |
-
from matris.model.reference_energy import AtomRef
|
| 22 |
-
from matris_dataset import MatRISDataset, matris_collate_fn, move_matris_batch_to_device
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
TRAIN_PATH = "datasets/trainingset_251216_train.xyz"
|
| 26 |
-
VAL_PATH = "datasets/trainingset_251216_val.xyz"
|
| 27 |
-
|
| 28 |
-
PROJECT_NAME = "matris-minimal-training"
|
| 29 |
-
RUN_NAME = "matris-ef-ddp"
|
| 30 |
-
|
| 31 |
-
BATCH_SIZE = 1
|
| 32 |
-
NUM_WORKERS = 0
|
| 33 |
-
EPOCHS = 1000
|
| 34 |
-
LR = 3e-4
|
| 35 |
-
MIN_LR = 3e-6
|
| 36 |
-
WEIGHT_DECAY = 1e-2
|
| 37 |
-
SEED = 42
|
| 38 |
-
|
| 39 |
-
ENERGY_LOSS_WEIGHT = 1.0
|
| 40 |
-
FORCE_LOSS_WEIGHT = 1.0
|
| 41 |
-
|
| 42 |
-
SAVE_DIR = Path("checkpoints_matris")
|
| 43 |
-
SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
| 44 |
-
|
| 45 |
-
E0S_DEFAULT = {
|
| 46 |
-
1: 2.467478445,
|
| 47 |
-
6: 8.0273263225,
|
| 48 |
-
8: 3.334308855,
|
| 49 |
-
22: 4.879036065,
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
def setup_ddp():
|
| 54 |
-
dist.init_process_group(backend="nccl")
|
| 55 |
-
local_rank = int(os.environ["LOCAL_RANK"])
|
| 56 |
-
rank = int(os.environ["RANK"])
|
| 57 |
-
world_size = int(os.environ["WORLD_SIZE"])
|
| 58 |
-
torch.cuda.set_device(local_rank)
|
| 59 |
-
device = f"cuda:{local_rank}"
|
| 60 |
-
return local_rank, rank, world_size, device
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def cleanup_ddp():
|
| 64 |
-
if dist.is_initialized():
|
| 65 |
-
dist.destroy_process_group()
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
def is_main_process():
|
| 69 |
-
return (not dist.is_initialized()) or dist.get_rank() == 0
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def reduce_mean(value: float, device: str) -> float:
|
| 73 |
-
tensor = torch.tensor(value, device=device, dtype=torch.float32)
|
| 74 |
-
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
|
| 75 |
-
tensor /= dist.get_world_size()
|
| 76 |
-
return tensor.item()
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
def set_seed(seed: int) -> None:
|
| 80 |
-
rank = dist.get_rank() if dist.is_initialized() else 0
|
| 81 |
-
seed = seed + rank
|
| 82 |
-
|
| 83 |
-
random.seed(seed)
|
| 84 |
-
np.random.seed(seed)
|
| 85 |
-
torch.manual_seed(seed)
|
| 86 |
-
torch.cuda.manual_seed_all(seed)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def unwrap_model(model):
|
| 90 |
-
return model.module if isinstance(model, DDP) else model
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
def build_reference_energy_module(model: MatRIS, e0_dict: dict[int, float]) -> AtomRef:
|
| 94 |
-
atom_ref = AtomRef(reference_energy="mptrj", is_intensive=model.is_intensive)
|
| 95 |
-
|
| 96 |
-
weight = torch.zeros(94, dtype=torch.float32)
|
| 97 |
-
for Z, e0 in e0_dict.items():
|
| 98 |
-
weight[Z - 1] = e0
|
| 99 |
-
|
| 100 |
-
state_dict = collections.OrderedDict()
|
| 101 |
-
state_dict["weight"] = weight.view(1, 94)
|
| 102 |
-
atom_ref.fc.load_state_dict(state_dict)
|
| 103 |
-
|
| 104 |
-
atom_ref.fitted = True
|
| 105 |
-
for p in atom_ref.parameters():
|
| 106 |
-
p.requires_grad = False
|
| 107 |
-
|
| 108 |
-
return atom_ref
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
class WeightedEnergyForcesMAELoss(nn.Module):
|
| 112 |
-
def __init__(self, energy_weight: float = 1.0, forces_weight: float = 1.0):
|
| 113 |
-
super().__init__()
|
| 114 |
-
self.energy_weight = energy_weight
|
| 115 |
-
self.forces_weight = forces_weight
|
| 116 |
-
|
| 117 |
-
def forward(
|
| 118 |
-
self,
|
| 119 |
-
model: MatRIS,
|
| 120 |
-
batch: dict,
|
| 121 |
-
out: dict,
|
| 122 |
-
do_eval: bool = False,
|
| 123 |
-
):
|
| 124 |
-
n_atoms = out["atoms_per_graph"].float()
|
| 125 |
-
|
| 126 |
-
if model.is_intensive:
|
| 127 |
-
pred_energy_per_atom = out["e"]
|
| 128 |
-
pred_total_energy = out["e"] * n_atoms
|
| 129 |
-
else:
|
| 130 |
-
pred_total_energy = out["e"]
|
| 131 |
-
pred_energy_per_atom = pred_total_energy / n_atoms
|
| 132 |
-
|
| 133 |
-
ref_total_energy = batch["energy"]
|
| 134 |
-
ref_energy_per_atom = ref_total_energy / n_atoms
|
| 135 |
-
|
| 136 |
-
force_losses = []
|
| 137 |
-
for pred_f, ref_f in zip(out["f"], batch["forces"]):
|
| 138 |
-
force_losses.append(torch.abs(pred_f - ref_f).mean())
|
| 139 |
-
|
| 140 |
-
loss_forces = torch.stack(force_losses).mean()
|
| 141 |
-
|
| 142 |
-
loss_energy = torch.mean(
|
| 143 |
-
torch.abs(pred_energy_per_atom - ref_energy_per_atom)
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
total_loss = (
|
| 147 |
-
self.forces_weight * loss_forces
|
| 148 |
-
+ self.energy_weight * loss_energy
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
return (
|
| 152 |
-
total_loss,
|
| 153 |
-
loss_energy,
|
| 154 |
-
loss_forces,
|
| 155 |
-
pred_total_energy,
|
| 156 |
-
ref_total_energy,
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
def run_epoch(
|
| 161 |
-
model: DDP,
|
| 162 |
-
loader: DataLoader,
|
| 163 |
-
optimizer: torch.optim.Optimizer | None,
|
| 164 |
-
scheduler: torch.optim.lr_scheduler._LRScheduler | None,
|
| 165 |
-
criterion: WeightedEnergyForcesMAELoss,
|
| 166 |
-
device: str,
|
| 167 |
-
epoch: int,
|
| 168 |
-
split: str,
|
| 169 |
-
) -> dict[str, float]:
|
| 170 |
-
is_train = optimizer is not None
|
| 171 |
-
model.train(is_train)
|
| 172 |
-
|
| 173 |
-
raw_model = unwrap_model(model)
|
| 174 |
-
|
| 175 |
-
running = {
|
| 176 |
-
"loss": 0.0,
|
| 177 |
-
"energy_mae_per_atom": 0.0,
|
| 178 |
-
"force_mae_per_component": 0.0,
|
| 179 |
-
"pred_total_energy_mean": 0.0,
|
| 180 |
-
"target_total_energy_mean": 0.0,
|
| 181 |
-
"ref_energy_mean": 0.0,
|
| 182 |
-
"lr": 0.0,
|
| 183 |
-
}
|
| 184 |
-
|
| 185 |
-
n_batches = 0
|
| 186 |
-
|
| 187 |
-
iterator = tqdm(loader, desc=f"Running {split}", disable=not is_main_process())
|
| 188 |
-
|
| 189 |
-
for batch in iterator:
|
| 190 |
-
if batch is None:
|
| 191 |
-
continue
|
| 192 |
-
|
| 193 |
-
batch = move_matris_batch_to_device(batch, device=device)
|
| 194 |
-
|
| 195 |
-
if is_train:
|
| 196 |
-
optimizer.zero_grad(set_to_none=True)
|
| 197 |
-
|
| 198 |
-
# Conservative forces need gradients even during validation.
|
| 199 |
-
if is_train or raw_model.force_stress_head.is_conservation:
|
| 200 |
-
with torch.enable_grad():
|
| 201 |
-
out = model(batch["graphs"], task="ef", is_training=is_train)
|
| 202 |
-
else:
|
| 203 |
-
with torch.no_grad():
|
| 204 |
-
out = model(batch["graphs"], task="ef", is_training=False)
|
| 205 |
-
|
| 206 |
-
loss, energy_loss, force_loss, pred_total_energy, target_total_energy = criterion(
|
| 207 |
-
model=raw_model,
|
| 208 |
-
batch=batch,
|
| 209 |
-
out=out,
|
| 210 |
-
do_eval=False,
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
if is_train:
|
| 214 |
-
loss.backward()
|
| 215 |
-
optimizer.step()
|
| 216 |
-
|
| 217 |
-
current_lr = optimizer.param_groups[0]["lr"] if is_train else 0.0
|
| 218 |
-
|
| 219 |
-
running["loss"] += loss.detach().item()
|
| 220 |
-
running["energy_mae_per_atom"] += energy_loss.detach().item()
|
| 221 |
-
running["force_mae_per_component"] += force_loss.detach().item()
|
| 222 |
-
running["pred_total_energy_mean"] += pred_total_energy.detach().mean().item()
|
| 223 |
-
running["target_total_energy_mean"] += target_total_energy.detach().mean().item()
|
| 224 |
-
|
| 225 |
-
ref_energy = out["ref_energy"]
|
| 226 |
-
if torch.is_tensor(ref_energy):
|
| 227 |
-
running["ref_energy_mean"] += ref_energy.detach().mean().item()
|
| 228 |
-
else:
|
| 229 |
-
running["ref_energy_mean"] += float(ref_energy)
|
| 230 |
-
|
| 231 |
-
running["lr"] += current_lr
|
| 232 |
-
n_batches += 1
|
| 233 |
-
|
| 234 |
-
del out, loss, energy_loss, force_loss, pred_total_energy, target_total_energy
|
| 235 |
-
|
| 236 |
-
if n_batches == 0:
|
| 237 |
-
raise RuntimeError(f"No batches found in {split} loader on rank {dist.get_rank()}.")
|
| 238 |
-
|
| 239 |
-
metrics = {k: v / n_batches for k, v in running.items()}
|
| 240 |
-
metrics["epoch"] = epoch
|
| 241 |
-
|
| 242 |
-
# Average metrics across GPUs.
|
| 243 |
-
for k in list(metrics.keys()):
|
| 244 |
-
if k != "epoch":
|
| 245 |
-
metrics[k] = reduce_mean(metrics[k], device=device)
|
| 246 |
-
|
| 247 |
-
if is_train and scheduler is not None:
|
| 248 |
-
scheduler.step()
|
| 249 |
-
|
| 250 |
-
if is_main_process():
|
| 251 |
-
wandb.log({f"{split}/{k}": v for k, v in metrics.items()}, step=epoch)
|
| 252 |
-
|
| 253 |
-
return metrics
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
def parse_args():
|
| 257 |
-
parser = argparse.ArgumentParser(description="Train MatRIS on energy/force data with DDP.")
|
| 258 |
-
|
| 259 |
-
parser.add_argument("--train_path", type=str, default=TRAIN_PATH)
|
| 260 |
-
parser.add_argument("--val_path", type=str, default=VAL_PATH)
|
| 261 |
-
|
| 262 |
-
parser.add_argument("--project_name", type=str, default=PROJECT_NAME)
|
| 263 |
-
parser.add_argument("--run_name", type=str, default=RUN_NAME)
|
| 264 |
-
|
| 265 |
-
parser.add_argument("--batch_size", type=int, default=BATCH_SIZE)
|
| 266 |
-
parser.add_argument("--num_workers", type=int, default=NUM_WORKERS)
|
| 267 |
-
parser.add_argument("--epochs", type=int, default=EPOCHS)
|
| 268 |
-
|
| 269 |
-
parser.add_argument("--lr", type=float, default=LR)
|
| 270 |
-
parser.add_argument("--min_lr", type=float, default=MIN_LR)
|
| 271 |
-
parser.add_argument("--weight_decay", type=float, default=WEIGHT_DECAY)
|
| 272 |
-
|
| 273 |
-
parser.add_argument("--energy_weight", type=float, default=ENERGY_LOSS_WEIGHT)
|
| 274 |
-
parser.add_argument("--force_weight", type=float, default=FORCE_LOSS_WEIGHT)
|
| 275 |
-
|
| 276 |
-
parser.add_argument("--seed", type=int, default=SEED)
|
| 277 |
-
parser.add_argument("--save_dir", type=str, default=str(SAVE_DIR))
|
| 278 |
-
|
| 279 |
-
parser.add_argument(
|
| 280 |
-
"--is_conservative",
|
| 281 |
-
action=argparse.BooleanOptionalAction,
|
| 282 |
-
default=True,
|
| 283 |
-
)
|
| 284 |
-
|
| 285 |
-
parser.add_argument(
|
| 286 |
-
"--use_reference_energy",
|
| 287 |
-
action=argparse.BooleanOptionalAction,
|
| 288 |
-
default=True,
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
parser.add_argument(
|
| 292 |
-
"--model_name",
|
| 293 |
-
type=str,
|
| 294 |
-
default=None,
|
| 295 |
-
)
|
| 296 |
-
|
| 297 |
-
parser.add_argument(
|
| 298 |
-
"--find_unused_parameters",
|
| 299 |
-
action=argparse.BooleanOptionalAction,
|
| 300 |
-
default=True,
|
| 301 |
-
help="Useful if some heads/branches are unused.",
|
| 302 |
-
)
|
| 303 |
-
|
| 304 |
-
return parser.parse_args()
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
def main():
|
| 308 |
-
local_rank, rank, world_size, device = setup_ddp()
|
| 309 |
-
args = parse_args()
|
| 310 |
-
|
| 311 |
-
set_seed(args.seed)
|
| 312 |
-
|
| 313 |
-
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
| 314 |
-
run_dir = Path(args.save_dir) / f"{args.run_name}_{timestamp}"
|
| 315 |
-
|
| 316 |
-
if is_main_process():
|
| 317 |
-
run_dir.mkdir(parents=True, exist_ok=True)
|
| 318 |
-
print(f"Saving checkpoints to: {run_dir}")
|
| 319 |
-
print(f"World size: {world_size}")
|
| 320 |
-
print(f"Per-GPU batch size: {args.batch_size}")
|
| 321 |
-
print(f"Effective batch size: {args.batch_size * world_size}")
|
| 322 |
-
|
| 323 |
-
wandb.init(
|
| 324 |
-
project=args.project_name,
|
| 325 |
-
name=args.run_name,
|
| 326 |
-
config=vars(args) | {
|
| 327 |
-
"scheduler": "CosineAnnealingLR",
|
| 328 |
-
"loss": "forces_mae + energy_mae_per_atom",
|
| 329 |
-
"world_size": world_size,
|
| 330 |
-
"effective_batch_size": args.batch_size * world_size,
|
| 331 |
-
},
|
| 332 |
-
)
|
| 333 |
-
|
| 334 |
-
if args.model_name is None or args.model_name == "none":
|
| 335 |
-
if is_main_process():
|
| 336 |
-
print("Training from scratch")
|
| 337 |
-
model = MatRIS(is_conservation=args.is_conservative)
|
| 338 |
-
else:
|
| 339 |
-
if is_main_process():
|
| 340 |
-
print(f"Starting from foundation model: {args.model_name}")
|
| 341 |
-
model = MatRIS.load(
|
| 342 |
-
args.model_name,
|
| 343 |
-
device="cpu",
|
| 344 |
-
cache_dir="foundation_models",
|
| 345 |
-
)
|
| 346 |
-
model.force_stress_head.is_conservation = args.is_conservative
|
| 347 |
-
|
| 348 |
-
if args.use_reference_energy:
|
| 349 |
-
model.reference_energy = build_reference_energy_module(model, E0S_DEFAULT)
|
| 350 |
-
else:
|
| 351 |
-
model.reference_energy = None
|
| 352 |
-
|
| 353 |
-
model = model.to(device)
|
| 354 |
-
|
| 355 |
-
model = DDP(
|
| 356 |
-
model,
|
| 357 |
-
device_ids=[local_rank],
|
| 358 |
-
output_device=local_rank,
|
| 359 |
-
find_unused_parameters=args.find_unused_parameters,
|
| 360 |
-
)
|
| 361 |
-
|
| 362 |
-
raw_model = unwrap_model(model)
|
| 363 |
-
|
| 364 |
-
if is_main_process():
|
| 365 |
-
print("Loaded config is_conservation:", raw_model.config.get("is_conservation"))
|
| 366 |
-
print("Actual force head is_conservation:", raw_model.force_stress_head.is_conservation)
|
| 367 |
-
print("Model is_intensive:", raw_model.is_intensive)
|
| 368 |
-
print(f"Using device: {device}")
|
| 369 |
-
|
| 370 |
-
train_dataset = MatRISDataset(args.train_path, model=raw_model)
|
| 371 |
-
val_dataset = MatRISDataset(args.val_path, model=raw_model)
|
| 372 |
-
|
| 373 |
-
train_sampler = DistributedSampler(
|
| 374 |
-
train_dataset,
|
| 375 |
-
num_replicas=world_size,
|
| 376 |
-
rank=rank,
|
| 377 |
-
shuffle=True,
|
| 378 |
-
drop_last=False,
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
val_sampler = DistributedSampler(
|
| 382 |
-
val_dataset,
|
| 383 |
-
num_replicas=world_size,
|
| 384 |
-
rank=rank,
|
| 385 |
-
shuffle=False,
|
| 386 |
-
drop_last=False,
|
| 387 |
-
)
|
| 388 |
-
|
| 389 |
-
train_loader = DataLoader(
|
| 390 |
-
train_dataset,
|
| 391 |
-
batch_size=args.batch_size,
|
| 392 |
-
sampler=train_sampler,
|
| 393 |
-
shuffle=False,
|
| 394 |
-
num_workers=args.num_workers,
|
| 395 |
-
collate_fn=matris_collate_fn,
|
| 396 |
-
pin_memory=True,
|
| 397 |
-
)
|
| 398 |
-
|
| 399 |
-
val_loader = DataLoader(
|
| 400 |
-
val_dataset,
|
| 401 |
-
batch_size=args.batch_size,
|
| 402 |
-
sampler=val_sampler,
|
| 403 |
-
shuffle=False,
|
| 404 |
-
num_workers=args.num_workers,
|
| 405 |
-
collate_fn=matris_collate_fn,
|
| 406 |
-
pin_memory=True,
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
optimizer = torch.optim.AdamW(
|
| 410 |
-
model.parameters(),
|
| 411 |
-
lr=args.lr,
|
| 412 |
-
weight_decay=args.weight_decay,
|
| 413 |
-
)
|
| 414 |
-
|
| 415 |
-
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
|
| 416 |
-
optimizer,
|
| 417 |
-
T_max=args.epochs,
|
| 418 |
-
eta_min=args.min_lr,
|
| 419 |
-
)
|
| 420 |
-
|
| 421 |
-
criterion = WeightedEnergyForcesMAELoss(
|
| 422 |
-
energy_weight=args.energy_weight,
|
| 423 |
-
forces_weight=args.force_weight,
|
| 424 |
-
)
|
| 425 |
-
|
| 426 |
-
if is_main_process():
|
| 427 |
-
print(f"Conservative forces: {args.is_conservative}")
|
| 428 |
-
print(f"Train size: {len(train_dataset)}")
|
| 429 |
-
print(f"Val size: {len(val_dataset)}")
|
| 430 |
-
|
| 431 |
-
best_checkpoints = []
|
| 432 |
-
MAX_BEST_CKPTS = 5
|
| 433 |
-
|
| 434 |
-
for epoch in tqdm(
|
| 435 |
-
range(1, args.epochs + 1),
|
| 436 |
-
desc="Epoch",
|
| 437 |
-
disable=not is_main_process(),
|
| 438 |
-
):
|
| 439 |
-
train_sampler.set_epoch(epoch)
|
| 440 |
-
|
| 441 |
-
train_metrics = run_epoch(
|
| 442 |
-
model=model,
|
| 443 |
-
loader=train_loader,
|
| 444 |
-
optimizer=optimizer,
|
| 445 |
-
scheduler=scheduler,
|
| 446 |
-
criterion=criterion,
|
| 447 |
-
device=device,
|
| 448 |
-
epoch=epoch,
|
| 449 |
-
split="train",
|
| 450 |
-
)
|
| 451 |
-
|
| 452 |
-
val_metrics = run_epoch(
|
| 453 |
-
model=model,
|
| 454 |
-
loader=val_loader,
|
| 455 |
-
optimizer=None,
|
| 456 |
-
scheduler=None,
|
| 457 |
-
criterion=criterion,
|
| 458 |
-
device=device,
|
| 459 |
-
epoch=epoch,
|
| 460 |
-
split="val",
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
current_lr = optimizer.param_groups[0]["lr"]
|
| 464 |
-
|
| 465 |
-
if is_main_process():
|
| 466 |
-
print(
|
| 467 |
-
f"Epoch {epoch:03d} | "
|
| 468 |
-
f"lr={current_lr:.2e} | "
|
| 469 |
-
f"train/loss={train_metrics['loss']:.6f} | "
|
| 470 |
-
f"train/e_per_atom={train_metrics['energy_mae_per_atom']:.6f} | "
|
| 471 |
-
f"train/f_per_component={train_metrics['force_mae_per_component']:.6f} | "
|
| 472 |
-
f"val/loss={val_metrics['loss']:.6f} | "
|
| 473 |
-
f"val/e_per_atom={val_metrics['energy_mae_per_atom']:.6f} | "
|
| 474 |
-
f"val/f_per_component={val_metrics['force_mae_per_component']:.6f}"
|
| 475 |
-
)
|
| 476 |
-
|
| 477 |
-
wandb.log({"epoch": epoch, "lr": current_lr}, step=epoch)
|
| 478 |
-
|
| 479 |
-
ckpt = {
|
| 480 |
-
"epoch": epoch,
|
| 481 |
-
"model_state_dict": raw_model.state_dict(),
|
| 482 |
-
"optimizer_state_dict": optimizer.state_dict(),
|
| 483 |
-
"scheduler_state_dict": scheduler.state_dict(),
|
| 484 |
-
"train_metrics": train_metrics,
|
| 485 |
-
"val_metrics": val_metrics,
|
| 486 |
-
"args": vars(args),
|
| 487 |
-
}
|
| 488 |
-
|
| 489 |
-
val_loss = val_metrics["loss"]
|
| 490 |
-
val_e = val_metrics["energy_mae_per_atom"]
|
| 491 |
-
val_f = val_metrics["force_mae_per_component"]
|
| 492 |
-
|
| 493 |
-
ckpt_name = (
|
| 494 |
-
f"best_epoch={epoch:04d}"
|
| 495 |
-
f"_val_loss={val_loss:.6f}"
|
| 496 |
-
f"_val_e_atom={val_e:.6f}"
|
| 497 |
-
f"_val_f_comp={val_f:.6f}.pt"
|
| 498 |
-
)
|
| 499 |
-
|
| 500 |
-
ckpt_path = run_dir / ckpt_name
|
| 501 |
-
|
| 502 |
-
should_save = False
|
| 503 |
-
|
| 504 |
-
if len(best_checkpoints) < MAX_BEST_CKPTS:
|
| 505 |
-
should_save = True
|
| 506 |
-
else:
|
| 507 |
-
worst_ckpt = max(best_checkpoints, key=lambda x: x["val_loss"])
|
| 508 |
-
if val_loss < worst_ckpt["val_loss"]:
|
| 509 |
-
if worst_ckpt["path"].exists():
|
| 510 |
-
worst_ckpt["path"].unlink()
|
| 511 |
-
best_checkpoints.remove(worst_ckpt)
|
| 512 |
-
should_save = True
|
| 513 |
-
|
| 514 |
-
if should_save:
|
| 515 |
-
torch.save(ckpt, ckpt_path)
|
| 516 |
-
|
| 517 |
-
best_checkpoints.append(
|
| 518 |
-
{
|
| 519 |
-
"path": ckpt_path,
|
| 520 |
-
"val_loss": val_loss,
|
| 521 |
-
"epoch": epoch,
|
| 522 |
-
}
|
| 523 |
-
)
|
| 524 |
-
|
| 525 |
-
best_checkpoints = sorted(best_checkpoints, key=lambda x: x["val_loss"])
|
| 526 |
-
|
| 527 |
-
print(f"Saved top-{MAX_BEST_CKPTS} checkpoint: {ckpt_name}")
|
| 528 |
-
|
| 529 |
-
wandb.run.summary["best_val_loss"] = best_checkpoints[0]["val_loss"]
|
| 530 |
-
wandb.run.summary["best_epoch"] = best_checkpoints[0]["epoch"]
|
| 531 |
-
|
| 532 |
-
dist.barrier()
|
| 533 |
-
|
| 534 |
-
if is_main_process():
|
| 535 |
-
wandb.finish()
|
| 536 |
-
|
| 537 |
-
cleanup_ddp()
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
if __name__ == "__main__":
|
| 541 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models/matris/scripts/bench_matris_speed_single.sh
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# =========================
|
| 5 |
+
# Resolve paths
|
| 6 |
+
# =========================
|
| 7 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 8 |
+
MATRIS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
| 9 |
+
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
|
| 10 |
+
|
| 11 |
+
# =========================
|
| 12 |
+
# Config
|
| 13 |
+
# =========================
|
| 14 |
+
BENCH_SCRIPT="$MATRIS_DIR/bench_matris_speed_single.py"
|
| 15 |
+
|
| 16 |
+
XYZ_PATH="$REPO_ROOT/datasets/xyz/test.xyz"
|
| 17 |
+
|
| 18 |
+
MODEL_NAME="none" # ["none", "matris_10m_oam", "matris_10m_mp"]
|
| 19 |
+
|
| 20 |
+
DEVICE="cpu"
|
| 21 |
+
|
| 22 |
+
TARGET_NATOMS=96
|
| 23 |
+
WARMUP=50
|
| 24 |
+
ITERS=300
|
| 25 |
+
|
| 26 |
+
IS_CONSERVATIVE=true
|
| 27 |
+
|
| 28 |
+
# =========================
|
| 29 |
+
# Flags
|
| 30 |
+
# =========================
|
| 31 |
+
CONSERVATIVE_FLAG="--is-conservative"
|
| 32 |
+
|
| 33 |
+
if [ "$IS_CONSERVATIVE" = false ]; then
|
| 34 |
+
CONSERVATIVE_FLAG=""
|
| 35 |
+
fi
|
| 36 |
+
|
| 37 |
+
# =========================
|
| 38 |
+
# Sanity checks
|
| 39 |
+
# =========================
|
| 40 |
+
if [ ! -f "$BENCH_SCRIPT" ]; then
|
| 41 |
+
echo "ERROR: Benchmark script not found:"
|
| 42 |
+
echo "$BENCH_SCRIPT"
|
| 43 |
+
exit 1
|
| 44 |
+
fi
|
| 45 |
+
|
| 46 |
+
if [ ! -f "$XYZ_PATH" ]; then
|
| 47 |
+
echo "ERROR: XYZ dataset not found:"
|
| 48 |
+
echo "$XYZ_PATH"
|
| 49 |
+
exit 1
|
| 50 |
+
fi
|
| 51 |
+
|
| 52 |
+
# =========================
|
| 53 |
+
# Run
|
| 54 |
+
# =========================
|
| 55 |
+
echo "======================================"
|
| 56 |
+
echo "Running MatRIS speed benchmark"
|
| 57 |
+
echo "Benchmark script: $BENCH_SCRIPT"
|
| 58 |
+
echo "XYZ path: $XYZ_PATH"
|
| 59 |
+
echo "Model: $MODEL_NAME"
|
| 60 |
+
echo "Device: $DEVICE"
|
| 61 |
+
echo "Target natoms: $TARGET_NATOMS"
|
| 62 |
+
echo "Warmup: $WARMUP"
|
| 63 |
+
echo "Iterations: $ITERS"
|
| 64 |
+
echo "Conservative: $IS_CONSERVATIVE"
|
| 65 |
+
echo "======================================"
|
| 66 |
+
|
| 67 |
+
python3 "$BENCH_SCRIPT" \
|
| 68 |
+
--xyz "$XYZ_PATH" \
|
| 69 |
+
--model-name "$MODEL_NAME" \
|
| 70 |
+
$CONSERVATIVE_FLAG \
|
| 71 |
+
--device "$DEVICE" \
|
| 72 |
+
--target-natoms "$TARGET_NATOMS" \
|
| 73 |
+
--warmup "$WARMUP" \
|
| 74 |
+
--iters "$ITERS"
|
models/matris/scripts/eval_matris.sh
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
set -e
|
| 4 |
+
|
| 5 |
+
# =========================
|
| 6 |
+
# Resolve paths
|
| 7 |
+
# =========================
|
| 8 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 9 |
+
MATRIS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
| 10 |
+
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
|
| 11 |
+
|
| 12 |
+
# =========================
|
| 13 |
+
# Config
|
| 14 |
+
# =========================
|
| 15 |
+
TEST_PATH="$REPO_ROOT/datasets/xyz/test.xyz"
|
| 16 |
+
|
| 17 |
+
CHECKPOINT="$MATRIS_DIR/runs/matris_cons_seed2000_epoch43.pt" # Add checkpoint here
|
| 18 |
+
|
| 19 |
+
EVAL_SCRIPT="$MATRIS_DIR/eval_matris.py"
|
| 20 |
+
|
| 21 |
+
RANDOM_INIT=false # true = evaluate random init model, false = load checkpoint
|
| 22 |
+
|
| 23 |
+
BATCH_SIZE=1
|
| 24 |
+
DEVICE="cuda"
|
| 25 |
+
|
| 26 |
+
IS_CONSERVATIVE=true # true = use conservative forces, false = use standard forces
|
| 27 |
+
USE_REFERENCE_ENERGY=true
|
| 28 |
+
|
| 29 |
+
MODEL_NAME="none" # ["none", "matris_10m_oam", "matris_10m_mp"]
|
| 30 |
+
|
| 31 |
+
# =========================
|
| 32 |
+
# Flags
|
| 33 |
+
# =========================
|
| 34 |
+
CONSERVATIVE_FLAG="--is_conservative"
|
| 35 |
+
if [ "$IS_CONSERVATIVE" = false ]; then
|
| 36 |
+
CONSERVATIVE_FLAG="--no-is_conservative"
|
| 37 |
+
fi
|
| 38 |
+
|
| 39 |
+
REF_FLAG="--use_reference_energy"
|
| 40 |
+
if [ "$USE_REFERENCE_ENERGY" = false ]; then
|
| 41 |
+
REF_FLAG="--no-use_reference_energy"
|
| 42 |
+
fi
|
| 43 |
+
|
| 44 |
+
RANDOM_INIT_ARGS=()
|
| 45 |
+
CHECKPOINT_ARGS=()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if [ "$RANDOM_INIT" = true ]; then
|
| 49 |
+
RANDOM_INIT_FLAG="--random_init"
|
| 50 |
+
else
|
| 51 |
+
CHECKPOINT_ARGS=(--checkpoint "$CHECKPOINT")
|
| 52 |
+
fi
|
| 53 |
+
|
| 54 |
+
# =========================
|
| 55 |
+
# Sanity checks
|
| 56 |
+
# =========================
|
| 57 |
+
if [ ! -f "$EVAL_SCRIPT" ]; then
|
| 58 |
+
echo "ERROR: Eval script not found:"
|
| 59 |
+
echo "$EVAL_SCRIPT"
|
| 60 |
+
exit 1
|
| 61 |
+
fi
|
| 62 |
+
|
| 63 |
+
if [ ! -f "$TEST_PATH" ]; then
|
| 64 |
+
echo "ERROR: Test dataset not found:"
|
| 65 |
+
echo "$TEST_PATH"
|
| 66 |
+
exit 1
|
| 67 |
+
fi
|
| 68 |
+
|
| 69 |
+
if [ "$RANDOM_INIT" = true ]; then
|
| 70 |
+
RANDOM_INIT_ARGS=(--random_init)
|
| 71 |
+
else
|
| 72 |
+
CHECKPOINT_ARGS=(--checkpoint "$CHECKPOINT")
|
| 73 |
+
fi
|
| 74 |
+
|
| 75 |
+
# =========================
|
| 76 |
+
# Run
|
| 77 |
+
# =========================
|
| 78 |
+
echo "======================================"
|
| 79 |
+
echo "Running MatRIS evaluation"
|
| 80 |
+
echo "Eval script: $EVAL_SCRIPT"
|
| 81 |
+
echo "Random init: $RANDOM_INIT"
|
| 82 |
+
|
| 83 |
+
if [ "$RANDOM_INIT" = true ]; then
|
| 84 |
+
echo "Checkpoint: <not used>"
|
| 85 |
+
else
|
| 86 |
+
echo "Checkpoint: $CHECKPOINT"
|
| 87 |
+
fi
|
| 88 |
+
|
| 89 |
+
echo "Test path: $TEST_PATH"
|
| 90 |
+
echo "Model name: $MODEL_NAME"
|
| 91 |
+
echo "Conservative: $IS_CONSERVATIVE"
|
| 92 |
+
echo "Reference energy: $USE_REFERENCE_ENERGY"
|
| 93 |
+
echo "======================================"
|
| 94 |
+
|
| 95 |
+
python3 "$EVAL_SCRIPT" \
|
| 96 |
+
--test_path "$TEST_PATH" \
|
| 97 |
+
"${CHECKPOINT_ARGS[@]}" \
|
| 98 |
+
--batch_size "$BATCH_SIZE" \
|
| 99 |
+
--model_name "$MODEL_NAME" \
|
| 100 |
+
--device "$DEVICE" \
|
| 101 |
+
"$CONSERVATIVE_FLAG" \
|
| 102 |
+
"$REF_FLAG" \
|
| 103 |
+
"${RANDOM_INIT_ARGS[@]}"
|
models/matris/scripts/run_matris.sh
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# =========================
|
| 4 |
+
# Resolve paths
|
| 5 |
+
# =========================
|
| 6 |
+
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 7 |
+
MATRIS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
| 8 |
+
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# =========================
|
| 13 |
+
# Default config
|
| 14 |
+
# =========================
|
| 15 |
+
TRAIN_PATH="$REPO_ROOT/datasets/xyz/train.xyz"
|
| 16 |
+
VAL_PATH="$REPO_ROOT/datasets/xyz/val.xyz"
|
| 17 |
+
SAVE_DIR="$MATRIS_DIR/checkpoints_matris"
|
| 18 |
+
TRAIN_SCRIPT="$MATRIS_DIR/run_matris.py"
|
| 19 |
+
FOUNDATION_MODELS_DIR="$MATRIS_DIR/foundation_models"
|
| 20 |
+
|
| 21 |
+
PROJECT_NAME="matris"
|
| 22 |
+
RUN_NAME="matris"
|
| 23 |
+
|
| 24 |
+
BATCH_SIZE=1 # per GPU
|
| 25 |
+
NUM_WORKERS=8
|
| 26 |
+
EPOCHS=100
|
| 27 |
+
LR=3e-4
|
| 28 |
+
MIN_LR=3e-6
|
| 29 |
+
WEIGHT_DECAY=1e-2
|
| 30 |
+
|
| 31 |
+
ENERGY_WEIGHT=5.0
|
| 32 |
+
FORCE_WEIGHT=5.0
|
| 33 |
+
|
| 34 |
+
SEED=42
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
IS_CONSERVATIVE=true
|
| 38 |
+
USE_REFERENCE_ENERGY=true
|
| 39 |
+
MODEL_NAME="matris_10m_oam" # ["none", "matris_10m_oam", "matris_10m_mp"]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# =========================
|
| 43 |
+
# Detect GPUs
|
| 44 |
+
# =========================
|
| 45 |
+
NUM_GPUS="${NUM_GPUS:-}"
|
| 46 |
+
|
| 47 |
+
if [ -z "$NUM_GPUS" ]; then
|
| 48 |
+
NUM_GPUS=$(python3 - <<'PY'
|
| 49 |
+
import torch
|
| 50 |
+
print(torch.cuda.device_count())
|
| 51 |
+
PY
|
| 52 |
+
)
|
| 53 |
+
fi
|
| 54 |
+
|
| 55 |
+
if [ "$NUM_GPUS" -lt 1 ]; then
|
| 56 |
+
echo "ERROR: No GPUs detected."
|
| 57 |
+
exit 1
|
| 58 |
+
fi
|
| 59 |
+
|
| 60 |
+
echo "Detected GPUs: $NUM_GPUS"
|
| 61 |
+
echo "Effective batch size: $((BATCH_SIZE * NUM_GPUS))"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# =========================
|
| 65 |
+
# Boolean flags
|
| 66 |
+
# =========================
|
| 67 |
+
CONSERVATIVE_FLAG="--is_conservative"
|
| 68 |
+
if [ "$IS_CONSERVATIVE" = false ]; then
|
| 69 |
+
CONSERVATIVE_FLAG="--no-is_conservative"
|
| 70 |
+
fi
|
| 71 |
+
|
| 72 |
+
REF_FLAG="--use_reference_energy"
|
| 73 |
+
if [ "$USE_REFERENCE_ENERGY" = false ]; then
|
| 74 |
+
REF_FLAG="--no-use_reference_energy"
|
| 75 |
+
fi
|
| 76 |
+
|
| 77 |
+
MODEL_FLAG=()
|
| 78 |
+
if [ -n "$MODEL_NAME" ]; then
|
| 79 |
+
MODEL_FLAG=(--model_name "$MODEL_NAME")
|
| 80 |
+
fi
|
| 81 |
+
|
| 82 |
+
# =========================
|
| 83 |
+
# Run DDP
|
| 84 |
+
# =========================
|
| 85 |
+
export WANDB__SERVICE_WAIT=300
|
| 86 |
+
export FOUNDATION_MODELS_DIR="$FOUNDATION_MODELS_DIR"
|
| 87 |
+
|
| 88 |
+
torchrun \
|
| 89 |
+
--standalone \
|
| 90 |
+
--nproc_per_node="$NUM_GPUS" \
|
| 91 |
+
"$TRAIN_SCRIPT" \
|
| 92 |
+
--train_path "$TRAIN_PATH" \
|
| 93 |
+
--val_path "$VAL_PATH" \
|
| 94 |
+
--project_name "$PROJECT_NAME" \
|
| 95 |
+
--run_name "$RUN_NAME" \
|
| 96 |
+
--batch_size "$BATCH_SIZE" \
|
| 97 |
+
--num_workers "$NUM_WORKERS" \
|
| 98 |
+
--epochs "$EPOCHS" \
|
| 99 |
+
--lr "$LR" \
|
| 100 |
+
--min_lr "$MIN_LR" \
|
| 101 |
+
--weight_decay "$WEIGHT_DECAY" \
|
| 102 |
+
--energy_weight "$ENERGY_WEIGHT" \
|
| 103 |
+
--force_weight "$FORCE_WEIGHT" \
|
| 104 |
+
--seed "$SEED" \
|
| 105 |
+
--save_dir "$SAVE_DIR" \
|
| 106 |
+
"$CONSERVATIVE_FLAG" \
|
| 107 |
+
"$REF_FLAG" \
|
| 108 |
+
"${MODEL_FLAG[@]}"
|