File size: 6,894 Bytes
7cbb55b | 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 | """
Training script for GINO on Car CFD dataset.
This script trains a Graph Neural Operator (GINO) on computational fluid
dynamics data for car pressure prediction. The model learns to predict
pressure fields from geometric inputs using graph-based representations.
"""
import torch
import wandb
import sys
from neuralop.training import setup, AdamW
from neuralop import get_model
from neuralop.utils import get_wandb_api_key
from neuralop.losses.data_losses import LpLoss
from neuralop.training.trainer import Trainer
from neuralop.data.datasets import CarCFDDataset
from neuralop.data.transforms.data_processors import DataProcessor
from copy import deepcopy
# query points is [sdf_query_resolution] * 3 (taken from config ahmed)
# Read the configuration
config_name = "cfd"
from zencfg import make_config_from_cli
import sys
sys.path.insert(0, "../")
from config.gino_carcfd_config import Default
config = make_config_from_cli(Default)
config = config.to_dict()
# Distributed training setup, if enabled
device, is_logger = setup(config)
# Model architecture adjustment for query resolution
if config.data.sdf_query_resolution < config.model.fno_n_modes[0]:
config.model.fno_n_modes = [config.data.sdf_query_resolution] * 3
# WandB logging configuration
wandb_init_args = {}
config_name = "car-pressure"
if config.wandb.log and is_logger:
wandb.login(key=get_wandb_api_key())
if config.wandb.name:
wandb_name = config.wandb.name
else:
wandb_name = "_".join(
f"{var}" for var in [config_name, config.data.sdf_query_resolution]
)
wandb_init_args = dict(
config=config,
name=wandb_name,
group=config.wandb.group,
project=config.wandb.project,
entity=config.wandb.entity,
)
if config.wandb.sweep:
for key in wandb.config.keys():
config.params[key] = wandb.config[key]
wandb.init(**wandb_init_args)
# Load CFD dataset
data_module = CarCFDDataset(
root_dir=config.data.root,
query_res=[config.data.sdf_query_resolution] * 3,
n_train=config.data.n_train,
n_test=config.data.n_test,
download=config.data.download,
)
# Create data loaders
train_loader = data_module.train_loader(batch_size=1, shuffle=True)
test_loader = data_module.test_loader(batch_size=1, shuffle=False)
# Model initialization
model = get_model(config)
# Create the optimizer
optimizer = AdamW(
model.parameters(),
lr=config.opt.learning_rate,
weight_decay=config.opt.weight_decay,
)
if config.opt.scheduler == "ReduceLROnPlateau":
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
optimizer,
factor=config.opt.gamma,
patience=config.opt.scheduler_patience,
mode="min",
)
elif config.opt.scheduler == "CosineAnnealingLR":
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=config.opt.scheduler_T_max
)
elif config.opt.scheduler == "StepLR":
scheduler = torch.optim.lr_scheduler.StepLR(
optimizer, step_size=config.opt.step_size, gamma=config.opt.gamma
)
else:
raise ValueError(f"Got {config.opt.scheduler=}")
l2loss = LpLoss(d=2, p=2)
if config.opt.training_loss == "l2":
train_loss_fn = l2loss
else:
raise ValueError(f"Got {config.opt.training_loss=}")
if config.opt.testing_loss == "l2":
test_loss_fn = l2loss
else:
raise ValueError(f"Got {config.opt.testing_loss=}")
# Custom data processor for GINO CFD training
class GINOCFDDataProcessor(DataProcessor):
"""
Data processor for GINO training on CFD car-pressure dataset.
This processor handles the conversion of CFD mesh data into the format
expected by the GINO model, including graph construction and
feature extraction from geometric inputs.
"""
def __init__(self, normalizer, device="cuda"):
super().__init__()
self.normalizer = normalizer
self.device = device
self.model = None
def preprocess(self, sample):
"""
Convert CFD mesh data into GINO input format.
Transforms the data dictionary from MeshDataModule's DictDataset
into the form expected by the GINO model.
"""
# input geometry: just vertices
in_p = sample["vertices"].squeeze(0).to(self.device)
latent_queries = sample["query_points"].squeeze(0).to(self.device)
out_p = sample["vertices"].squeeze(0).to(self.device)
f = sample["distance"].to(self.device)
# Output pressure data
truth = sample["press"].squeeze(0).unsqueeze(-1)
# Take the first 3586 vertices of the output mesh to correspond to pressure
# if there are less than 3586 vertices, take the maximum number of truth points
output_vertices = truth.shape[1]
if out_p.shape[0] > output_vertices:
out_p = out_p[:output_vertices, :]
truth = truth.to(device)
batch_dict = dict(
input_geom=in_p,
latent_queries=latent_queries,
output_queries=out_p,
latent_features=f,
y=truth,
x=None,
)
sample.update(batch_dict)
return sample
def postprocess(self, out, sample):
"""
Postprocess model output and ground truth data.
Applies inverse normalization to both predictions and ground truth
when not in training mode.
"""
if not self.training:
out = self.normalizer.inverse_transform(out)
y = self.normalizer.inverse_transform(sample["y"].squeeze(0))
sample["y"] = y
return out, sample
def to(self, device):
self.device = device
self.normalizer = self.normalizer.to(device)
return self
def wrap(self, model):
self.model = model
def forward(self, sample):
"""
Complete forward pass through the data processor and model.
"""
sample = self.preprocess(sample)
out = self.model(sample)
out, sample = self.postprocess(out, sample)
return out, sample
# Initialize data processor
output_encoder = deepcopy(data_module.normalizers["press"]).to(device)
data_processor = GINOCFDDataProcessor(normalizer=output_encoder, device=device)
# Trainer setup
trainer = Trainer(
model=model,
n_epochs=config.opt.n_epochs,
data_processor=data_processor,
device=device,
wandb_log=config.wandb.log,
verbose=is_logger,
)
# Log additional dataset information
if config.wandb.log:
wandb.log({"time_to_distance": data_module.time_to_distance}, commit=False)
# Start training process
trainer.train(
train_loader=train_loader,
test_loaders={"test": test_loader},
optimizer=optimizer,
scheduler=scheduler,
training_loss=train_loss_fn,
eval_losses={config.opt.testing_loss: test_loss_fn},
regularizer=None,
)
|