Files
thermal-conduction-ml/ThermalSolver/graph_module.py

120 lines
3.5 KiB
Python

import torch
from lightning import LightningModule
from torch_geometric.data import Batch
import importlib
def import_class(class_path: str):
module_path, class_name = class_path.rsplit(".", 1) # split last dot
module = importlib.import_module(module_path) # import the module
cls = getattr(module, class_name) # get the class
return cls
class GraphSolver(LightningModule):
def __init__(
self,
model_class_path: str,
model_init_args: dict,
loss: torch.nn.Module = None,
unrolling_steps: int = 48,
):
super().__init__()
self.model = import_class(model_class_path)(**model_init_args)
self.loss = loss if loss is not None else torch.nn.MSELoss()
self.unrolling_steps = unrolling_steps
def forward(
self,
x: torch.Tensor,
c: torch.Tensor,
edge_index: torch.Tensor,
edge_attr: torch.Tensor,
unrolling_steps: int = None,
boundary_mask: torch.Tensor = None,
):
return self.model(
x,
c,
edge_index,
edge_attr,
unrolling_steps,
boundary_mask=boundary_mask,
)
def _compute_loss(self, x, y):
return self.loss(x, y)
def _preprocess_batch(self, batch: Batch):
return batch.x, batch.y, batch.c, batch.edge_index, batch.edge_attr
def _log_loss(self, loss, batch, stage: str):
self.log(
f"{stage}/loss",
loss,
on_step=False,
on_epoch=True,
prog_bar=True,
batch_size=int(batch.num_graphs),
)
return loss
def training_step(self, batch: Batch, _):
x, y, c, edge_index, edge_attr = self._preprocess_batch(batch)
y_pred = self(
x,
c,
edge_index=edge_index,
edge_attr=edge_attr,
unrolling_steps=self.unrolling_steps,
boundary_mask=batch.boundary_mask,
)
loss = self.loss(y_pred, y)
boundary_loss = self.loss(
y_pred[batch.boundary_mask], y[batch.boundary_mask]
)
self._log_loss(loss, batch, "train")
self._log_loss(boundary_loss, batch, "train_boundary")
return loss
def validation_step(self, batch: Batch, _):
x, y, c, edge_index, edge_attr = self._preprocess_batch(batch)
y_pred = self(
x,
c,
edge_index=edge_index,
edge_attr=edge_attr,
unrolling_steps=self.unrolling_steps,
)
loss = self.loss(y_pred, y)
boundary_loss = self.loss(
y_pred[batch.boundary_mask], y[batch.boundary_mask]
)
self._log_loss(loss, batch, "val")
self._log_loss(boundary_loss, batch, "val_boundary")
return loss
def test_step(self, batch: Batch, _):
x, y, c, edge_index, edge_attr = self._preprocess_batch(batch)
y_pred = self.model(
x,
c,
edge_index=edge_index,
edge_attr=edge_attr,
unrolling_steps=self.unrolling_steps,
batch=batch.batch,
pos=batch.pos,
plot_results=True,
)
loss = self._compute_loss(y_pred, y)
self._log_loss(loss, batch, "test")
return loss
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
return optimizer
def _impose_bc(self, x: torch.Tensor, data: Batch):
x[data.boundary_mask] = data.boundary_values
return x