Compare commits

...

12 Commits

Author SHA1 Message Date
92104a6b06 new plotting strategy 2025-12-19 15:50:47 +01:00
68a7def5e6 add LogPhysEncoder 2025-12-19 15:50:26 +01:00
db50f5ed69 add experiments 2025-12-18 09:30:37 +01:00
0a034225ef not bad this setup 2025-12-18 09:30:21 +01:00
Filippo Olivo
4fdf817d75 add experiments for 10 unrolling steps 2025-12-15 09:15:29 +01:00
Filippo Olivo
a9d56a3ed9 fix model and datamodule 2025-12-15 09:08:21 +01:00
Filippo Olivo
3cc1d230e4 fix experiments 2025-12-12 10:18:49 +01:00
Filippo Olivo
732d48c360 new data format 2025-12-12 10:18:16 +01:00
Filippo Olivo
27c2aeb736 fix .gitignore 2025-12-09 09:46:14 +01:00
Filippo Olivo
7a2316da04 add experiments 2025-12-09 09:19:26 +01:00
Filippo Olivo
c1820d5855 fix training submission script 2025-12-09 09:19:12 +01:00
Filippo Olivo
f2ce282a68 fix module and model + add curriculum callback 2025-12-09 09:18:36 +01:00
23 changed files with 1120 additions and 442 deletions

1
.gitignore vendored
View File

@@ -210,6 +210,7 @@ __marimo__/
logs/
*.log
models/
logs*
# Images
*.png

View File

@@ -15,52 +15,102 @@ def import_class(class_path: str):
return cls
def _plot_mesh(pos_, y_, y_pred_, y_true_, batch, i, batch_idx):
for j in [0, 10, 20, 30]:
def _plot_mesh(pos_, y_, y_pred_, y_true_, batch, cells, i, batch_idx):
# print(pos_.shape, y_.shape, y_pred_.shape, y_true_.shape)
for j in [0]:
idx = (batch == j).nonzero(as_tuple=True)[0]
y = y_[idx].detach().cpu()
y_pred = y_pred_[idx].detach().cpu()
pos = pos_[idx].detach().cpu()
# print(pos.shape, y.shape, y_pred.shape)
y_true = y_true_[idx].detach().cpu()
y_true = torch.clamp(y_true, min=0)
folder = f"{j:02d}_images"
folder = f"{batch_idx:02d}_images"
if os.path.exists(folder) is False:
os.makedirs(folder)
pos = pos.detach().cpu()
tria = Triangulation(pos[:, 0], pos[:, 1])
plt.figure(figsize=(24, 5))
triangles = torch.vstack([cells[:, [0, 1, 2]], cells[:, [0, 2, 3]]])
tria = Triangulation(pos[:, 0], pos[:, 1], triangles=triangles)
plt.figure(figsize=(24, 6))
# plt.subplot(1, 4, 1)
# plt.tricontourf(tria, y.squeeze().numpy(), levels=100)
# plt.colorbar()
# plt.title("Step t-1")
# plt.tripcolor(tria, y_pred.squeeze().numpy()
# plt.savefig("test_scatter_step_before.png", dpi=72)
# x = z
plt.subplot(1, 4, 1)
plt.tricontourf(tria, y.squeeze().numpy(), levels=100)
plt.colorbar()
plt.title("Step t-1")
plt.subplot(1, 4, 2)
plt.tricontourf(tria, y_pred.squeeze().numpy(), levels=100)
# plt.scatter(pos[:, 0], pos[:, 1], c=y_pred.squeeze().numpy(), s=20, cmap="viridis",)
plt.colorbar()
plt.title("Step t Predicted")
plt.subplot(1, 4, 3)
plt.title(f"Prediction at timestep {i:03d}")
plt.subplot(1, 4, 2)
plt.tricontourf(tria, y_true.squeeze().numpy(), levels=100)
# plt.scatter(pos[:, 0], pos[:, 1], c=y_true.squeeze().numpy(), s=20, cmap="viridis")
plt.colorbar()
plt.title("t True")
plt.title("Ground Truth Steady State")
plt.subplot(1, 4, 3)
per_element_relative_error = torch.abs(y_pred - y_true) / (
y_true + 1e-6
)
per_element_relative_error = torch.clamp(
per_element_relative_error, max=1.0, min=0.0
)
plt.tricontourf(
tria,
per_element_relative_error.squeeze(),
levels=100,
vmin=0,
vmax=1.0,
)
# plt.scatter(pos[:, 0], pos[:, 1], c=per_element_relative_error.squeeze().numpy(), s=20, cmap="viridis", vmin=0, vmax=1.0)
plt.colorbar()
plt.title("Relative Error")
plt.subplot(1, 4, 4)
plt.tricontourf(tria, (y_true - y_pred).squeeze().numpy(), levels=100)
absolute_error = torch.abs(y_pred - y_true)
plt.tricontourf(tria, absolute_error.squeeze(), levels=100)
# plt.scatter(pos[:, 0], pos[:, 1], c=absolute_error.squeeze().numpy(), s=20, cmap="viridis")
plt.colorbar()
plt.title("Error")
plt.title("Absolute Error")
plt.suptitle("GNO", fontsize=16)
name = f"{folder}/{j:04d}_graph_iter_{i:04d}.png"
plt.savefig(name, dpi=72)
plt.close()
def _plot_losses(losses, batch_idx):
folder = f"{batch_idx:02d}_images"
plt.figure()
plt.plot(losses)
def _plot_losses(relative_errors, test_losses, relative_update, batch_idx):
# folder = f"{batch_idx:02d}_images"
plt.figure(figsize=(18, 6))
plt.subplot(1, 3, 1)
for i, losses in enumerate(test_losses):
plt.plot(losses)
if i == 3:
break
plt.yscale("log")
plt.xlabel("Iteration")
plt.ylabel("Loss")
plt.ylabel("Test Loss")
plt.title("Test Loss over Iterations")
plt.grid(True)
file_name = f"{folder}/test_loss.png"
plt.subplot(1, 3, 2)
for i, losses in enumerate(relative_errors):
plt.plot(losses)
if i == 3:
break
plt.yscale("log")
plt.xlabel("Iteration")
plt.ylabel("Relative Error")
plt.title("Relative error over Iterations")
plt.grid(True)
plt.subplot(1, 3, 3)
for i, updates in enumerate(relative_update):
plt.plot(updates)
if i == 3:
break
plt.yscale("log")
plt.xlabel("Iteration")
plt.ylabel("Relative Update")
plt.title("Relative update over Iterations")
plt.grid(True)
file_name = f"test_errors.png"
plt.savefig(file_name, dpi=300)
plt.close()
@@ -80,6 +130,9 @@ class GraphSolver(LightningModule):
# print(f"Param: {param[0]}")
self.loss = loss if loss is not None else torch.nn.MSELoss()
self.unrolling_steps = unrolling_steps
self.test_losses = []
self.test_relative_errors = []
self.test_relative_updates = []
def _compute_loss(self, x, y):
return self.loss(x, y)
@@ -116,13 +169,12 @@ class GraphSolver(LightningModule):
return out
def _preprocess_batch(self, batch: Batch):
x, y, c, edge_index, edge_attr, nodal_area = (
x, y, c, edge_index, edge_attr = (
batch.x,
batch.y,
batch.c,
batch.edge_index,
batch.edge_attr,
batch.nodal_area,
)
edge_attr = 1 / edge_attr
conductivity = self._compute_c_ij(c, edge_index)
@@ -133,35 +185,9 @@ class GraphSolver(LightningModule):
x, y, edge_index, edge_attr, conductivity = self._preprocess_batch(
batch
)
# deg = self._compute_deg(edge_index, edge_attr, x.size(0))
losses = []
# print(x.shape, y.shape)
# # print(torch.max(edge_index), torch.min(edge_index))
# plt.figure()
# plt.subplot(2,3,1)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=x.squeeze().cpu())
# plt.subplot(2,3,2)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=y[:,0,:].squeeze().cpu())
# plt.subplot(2,3,3)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=y[:,1,:].squeeze().cpu())
# plt.subplot(2,3,4)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=y[:,2,:].squeeze().cpu())
# plt.subplot(2,3,5)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=y[:,3,:].squeeze().cpu())
# plt.subplot(2,3,6)
# plt.scatter(batch.pos[:,0].cpu(), batch.pos[:,1].cpu(), c=y[:,4,:].squeeze().cpu())
# plt.suptitle("Training Batch Visualization", fontsize=16)
# plt.savefig("training_batch_visualization.png", dpi=300)
# plt.close()
# y = z
pos = batch.pos
boundary_mask = batch.boundary_mask
boundary_values = batch.boundary_values
# plt.scatter(pos[boundary_mask,0].cpu(), pos[boundary_mask,1].cpu(), c=boundary_values.cpu(), s=1)
# plt.savefig("boundary_nodes.png", dpi=300)
# y = z
scale = 50
for i in range(self.unrolling_steps):
# print(f"Training step {i+1}/{self.unrolling_steps}")
out = self._compute_model_steps(
x,
edge_index,
@@ -172,15 +198,26 @@ class GraphSolver(LightningModule):
conductivity,
)
x = out
# print(out.shape, y[:, i, :].shape)
losses.append(self.loss(out.flatten(), y[:, i, :].flatten()))
# print(self.model.scale_edge_attr.item())
loss = torch.stack(losses).mean()
# for param in self.model.parameters():
# print(f"Param: {param.shape}, Grad: {param.grad}")
# print(f"Param: {param[0]}")
self._log_loss(loss, batch, "train")
for i, layer in enumerate(self.model.layers):
self.log(
f"{i:03d}_alpha",
layer.alpha,
prog_bar=True,
on_epoch=True,
on_step=False,
batch_size=int(batch.num_graphs),
)
self.log(
"dt",
self.model.dt,
prog_bar=True,
on_epoch=True,
on_step=False,
batch_size=int(batch.num_graphs),
)
return loss
def validation_step(self, batch: Batch, batch_idx):
@@ -201,20 +238,20 @@ class GraphSolver(LightningModule):
batch.boundary_values,
conductivity,
)
if (
batch_idx == 0
and self.current_epoch % 10 == 0
and self.current_epoch > 0
):
_plot_mesh(
batch.pos,
x,
out,
y[:, i, :],
batch.batch,
i,
self.current_epoch,
)
# if (
# batch_idx == 0
# and self.current_epoch % 10 == 0
# and self.current_epoch > 0
# ):
# _plot_mesh(
# batch.pos,
# x,
# out,
# y[:, i, :],
# batch.batch,
# i,
# self.current_epoch,
# )
x = out
losses.append(self.loss(out, y[:, i, :]))
@@ -222,8 +259,81 @@ class GraphSolver(LightningModule):
self._log_loss(loss, batch, "val")
return loss
def _check_convergence(self, y_new, y_old, tol=1e-4):
l2_norm = torch.norm(y_new - y_old, p=2)
y_old_norm = torch.norm(y_old, p=2)
rel_error = l2_norm / (y_old_norm)
return rel_error.item() < tol, rel_error.item()
def test_step(self, batch: Batch, batch_idx):
pass
x, y, edge_index, edge_attr, conductivity = self._preprocess_batch(
batch
)
# deg = self._compute_deg(edge_index, edge_attr, x.size(0))
losses = []
all_losses = []
norms = []
s = []
relative_updates = []
sequence_length = y.size(1)
y = y[:, -1, :].unsqueeze(1)
_plot_mesh(
batch.pos, x, x, y[:, -1, :], batch.batch, batch.cells, 0, batch_idx
)
for i in range(200):
out = self._compute_model_steps(
# torch.cat([x,pos], dim=-1),
x,
edge_index,
edge_attr,
# deg,
batch.boundary_mask,
batch.boundary_values,
conductivity,
)
norms.append(torch.norm(out - x, p=2).item())
converged, relative_update = self._check_convergence(out, x)
relative_updates.append(relative_update)
if batch_idx <= 4:
print(f"Plotting iteration {i}, norm diff: {norms[-1]}")
_plot_mesh(
batch.pos,
x,
out,
y[:, -1, :],
batch.batch,
batch.cells,
i + 1,
batch_idx,
)
x = out
loss = self.loss(out, y[:, -1, :])
relative_error = torch.abs(out - y[:, -1, :]) / (
torch.abs(y[:, -1, :]) + 1e-6
)
mean_relative_error = relative_error.mean()
all_losses.append(mean_relative_error.item())
losses.append(loss)
if converged:
print(
f"Test step converged at iteration {i} for batch {batch_idx}"
)
break
loss = torch.stack(losses).mean()
self.test_losses.append(losses)
self.test_relative_errors.append(all_losses)
self.test_relative_updates.append(relative_updates)
self._log_loss(loss, batch, "test")
return loss
def on_test_end(self):
if len(self.test_losses) > 0:
_plot_losses(
self.test_relative_errors,
self.test_losses,
self.test_relative_updates,
batch_idx=0,
)
def configure_optimizers(self):
optimizer = torch.optim.AdamW(self.parameters(), lr=1e-3)

View File

@@ -82,7 +82,9 @@ class GraphDataModule(LightningDataModule):
conductivity = torch.tensor(
snapshot["conductivity"], dtype=torch.float32
)
temperature = torch.tensor(snapshot["temperature"], dtype=torch.float32)
temperature = torch.tensor(
snapshot["temperature"], dtype=torch.float32
)[:50]
pos = torch.tensor(geometry["points"], dtype=torch.float32)[:, :2]

View File

@@ -1,50 +1,20 @@
import torch
from tqdm import tqdm
from lightning import LightningDataModule
from datasets import load_dataset
from datasets import load_dataset, concatenate_datasets
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
from torch_geometric.utils import to_undirected
from .mesh_data import MeshData
# from torch.utils.data import Dataset
from torch_geometric.utils import scatter
def compute_nodal_area(edge_index, edge_attr, num_nodes):
"""
1. Calculates Area ~ (Min Edge Length)^2
2. Scales by Mean so average cell has size 1.0
"""
row, col = edge_index
dist = edge_attr.squeeze()
# 1. Get 'h' (Closest neighbor distance)
# Using 'min' filters out diagonal connections in the quad mesh
h = scatter(dist, col, dim=0, dim_size=num_nodes, reduce="min")
# 2. Estimate Raw Area
raw_area = h.pow(2)
# 3. Mean Scaling (The Best Normalization)
# This keeps values near 1.0, preserving stability AND physics ratios.
# We detach to ensure no gradients flow here (it's static data).
mean_val = raw_area.mean().detach()
# Result:
# Small cells -> approx 0.1
# Large cells -> approx 5.0
# Average -> 1.0
# nodal_area = (raw_area / mean_val).unsqueeze(-1) + 1e-6
nodal_area = raw_area
return nodal_area.unsqueeze(-1)
from typing import List, Union
class GraphDataModule(LightningDataModule):
def __init__(
self,
hf_repo: str,
split_name: str,
split_name: Union[str, List[str]],
n_elements: int = None,
train_size: float = 0.2,
val_size: float = 0.1,
test_size: float = 0.1,
@@ -52,18 +22,24 @@ class GraphDataModule(LightningDataModule):
remove_boundary_edges: bool = False,
build_radial_graph: bool = False,
radius: float = None,
start_unrolling_steps: int = 1,
unrolling_steps: int = 1,
aggregate_timesteps: int = 1,
min_normalized_diff: float = 1e-3,
):
super().__init__()
self.hf_repo = hf_repo
self.split_name = split_name
self.n_elements = n_elements
self.dataset_dict = {}
self.train_dataset, self.val_dataset, self.test_dataset = (
None,
None,
None,
)
self.unrolling_steps = start_unrolling_steps
self.unrolling_steps = unrolling_steps
self.aggregate_timesteps = aggregate_timesteps
self.min_normalized_diff = min_normalized_diff
self.geometry_dict = {}
self.train_size = train_size
self.val_size = val_size
@@ -74,8 +50,33 @@ class GraphDataModule(LightningDataModule):
self.radius = radius
def prepare_data(self):
dataset = load_dataset(self.hf_repo, name="snapshots")[self.split_name]
geometry = load_dataset(self.hf_repo, name="geometry")[self.split_name]
if isinstance(self.split_name, list):
dataset_list = []
geometry_list = []
for split in self.split_name:
dataset_list.append(
load_dataset(self.hf_repo, name="snapshots")[split]
)
geometry_list.append(
load_dataset(self.hf_repo, name="geometry")[split]
)
dataset = concatenate_datasets(dataset_list)
geometry = concatenate_datasets(geometry_list)
idx = torch.randperm(len(dataset))
dataset = dataset.select(idx.tolist())
geometry = geometry.select(idx.tolist())
else:
dataset = load_dataset(self.hf_repo, name="snapshots")[
self.split_name
]
geometry = load_dataset(self.hf_repo, name="geometry")[
self.split_name
]
if self.n_elements is not None:
dataset = dataset.select(range(self.n_elements))
geometry = geometry.select(range(self.n_elements))
total_len = len(dataset)
train_len = int(self.train_size * total_len)
@@ -91,63 +92,39 @@ class GraphDataModule(LightningDataModule):
"test": geometry.select(range(train_len + valid_len, total_len)),
}
def _compute_boundary_mask(
self, bottom_ids, right_ids, top_ids, left_ids, temperature
):
left_ids = left_ids[~torch.isin(left_ids, bottom_ids)]
right_ids = right_ids[~torch.isin(right_ids, bottom_ids)]
left_ids = left_ids[~torch.isin(left_ids, top_ids)]
right_ids = right_ids[~torch.isin(right_ids, top_ids)]
bottom_bc = temperature[bottom_ids].median()
bottom_bc_mask = torch.ones(len(bottom_ids)) * bottom_bc
left_bc = temperature[left_ids].median()
left_bc_mask = torch.ones(len(left_ids)) * left_bc
right_bc = temperature[right_ids].median()
right_bc_mask = torch.ones(len(right_ids)) * right_bc
boundary_values = torch.cat(
[bottom_bc_mask, right_bc_mask, left_bc_mask], dim=0
)
boundary_mask = torch.cat([bottom_ids, right_ids, left_ids], dim=0)
return boundary_mask, boundary_values
def _build_dataset(
self,
snapshot: dict,
geometry: dict,
test: bool = False,
) -> Data:
conductivity = torch.tensor(
geometry["conductivity"], dtype=torch.float32
)
temperatures = torch.tensor(
snapshot["temperatures"], dtype=torch.float32
)[:40]
times = torch.tensor(snapshot["times"], dtype=torch.float32)
temperatures = (
torch.tensor(snapshot["unsteady"], dtype=torch.float32)
if not test
else torch.stack(
[
torch.tensor(snapshot["unsteady"], dtype=torch.float32)[
0, ...
],
torch.tensor(snapshot["steady"], dtype=torch.float32),
],
dim=0,
)
)
if not test:
for t in range(1, temperatures.size(0)):
diff = temperatures[t, :] - temperatures[t - 1, :]
norm_diff = torch.norm(diff, p=2) / torch.norm(
temperatures[t - 1], p=2
)
if norm_diff < self.min_normalized_diff:
temperatures = temperatures[: t + 1, :]
break
pos = torch.tensor(geometry["points"], dtype=torch.float32)[:, :2]
bottom_ids = torch.tensor(
geometry["bottom_boundary_ids"], dtype=torch.long
)
top_ids = torch.tensor(geometry["top_boundary_ids"], dtype=torch.long)
left_ids = torch.tensor(geometry["left_boundary_ids"], dtype=torch.long)
right_ids = torch.tensor(
geometry["right_boundary_ids"], dtype=torch.long
)
if self.build_radial_graph:
# from pina.graph import RadiusGraph
# if self.radius is None:
# raise ValueError("Radius must be specified for radial graph.")
# edge_index = RadiusGraph.compute_radius_graph(
# pos, radius=self.radius
# )
# from torch_geometric.utils import remove_self_loops
# edge_index, _ = remove_self_loops(edge_index)
raise NotImplementedError(
"Radial graph building not implemented yet."
)
@@ -157,18 +134,39 @@ class GraphDataModule(LightningDataModule):
).T
edge_index = to_undirected(edge_index, num_nodes=pos.size(0))
boundary_mask, boundary_values = self._compute_boundary_mask(
bottom_ids, right_ids, top_ids, left_ids, temperatures[0, :]
boundary_mask = torch.tensor(
geometry["constraints_mask"], dtype=torch.int64
)
boundary_values = temperatures[0, boundary_mask]
edge_attr = torch.norm(pos[edge_index[0]] - pos[edge_index[1]], dim=1)
nodal_area = compute_nodal_area(edge_index, edge_attr, pos.size(0))
if self.remove_boundary_edges:
boundary_idx = torch.unique(boundary_mask)
edge_index_mask = ~torch.isin(edge_index[1], boundary_idx)
edge_index = edge_index[:, edge_index_mask]
edge_attr = edge_attr[edge_index_mask]
n_data = temperatures.size(0) - self.unrolling_steps
n_data = max(temperatures.size(0) - self.unrolling_steps, 1)
data = []
if test:
cells = geometry.get("cells", None)
if cells is not None:
cells = torch.tensor(cells, dtype=torch.int64)
data.append(
MeshData(
x=temperatures[0, :].unsqueeze(-1),
y=temperatures[1:2, :].unsqueeze(-1).permute(1, 0, 2),
c=conductivity.unsqueeze(-1),
edge_index=edge_index,
pos=pos,
edge_attr=edge_attr,
boundary_mask=boundary_mask,
boundary_values=boundary_values,
cells=cells,
)
)
return data
for i in range(n_data):
x = temperatures[i, :].unsqueeze(-1)
y = (
@@ -186,7 +184,6 @@ class GraphDataModule(LightningDataModule):
edge_attr=edge_attr,
boundary_mask=boundary_mask,
boundary_values=boundary_values,
nodal_area=nodal_area,
)
)
return data
@@ -213,7 +210,7 @@ class GraphDataModule(LightningDataModule):
]
if stage == "test" or stage is None:
self.test_data = [
self._build_dataset(snap, geom)
self._build_dataset(snap, geom, test=True)
for snap, geom in tqdm(
zip(self.dataset_dict["test"], self.geometry_dict["test"]),
desc="Building test graphs",
@@ -234,33 +231,36 @@ class GraphDataModule(LightningDataModule):
# self.train_dataset = ds
# print(type(self.train_data[0]))
ds = [i for data in self.train_data for i in data]
# print(type(ds[0]))
print(
f"\nLoading training data, using {self.unrolling_steps} unrolling steps..."
)
return DataLoader(
ds,
batch_size=self.batch_size,
shuffle=True,
num_workers=8,
pin_memory=True,
pin_memory=False,
)
def val_dataloader(self):
print(
f"\nLoading validation data, using {self.unrolling_steps} unrolling steps..."
)
ds = [i for data in self.val_data for i in data]
return DataLoader(
ds,
batch_size=128,
shuffle=False,
num_workers=8,
pin_memory=True,
pin_memory=False,
)
def test_dataloader(self):
ds = self.create_autoregressive_datasets(
dataset="test", no_unrolling=True
)
ds = [i for data in self.test_data for i in data]
return DataLoader(
ds,
batch_size=self.batch_size,
batch_size=1,
shuffle=False,
num_workers=8,
pin_memory=True,
pin_memory=False,
)

View File

@@ -1,6 +1,28 @@
import torch
import torch.nn as nn
from torch_geometric.nn import MessagePassing
from torch.nn.utils import spectral_norm
class LogPhysEncoder(nn.Module):
"""
Processes 1/dx in log-space to handle multiple scales of geometry
(from micro-meshes to macro-meshes) without numerical instability.
"""
def __init__(self, hidden_dim):
super().__init__()
self.mlp = nn.Sequential(
spectral_norm(nn.Linear(1, hidden_dim)),
nn.GELU(),
spectral_norm(nn.Linear(hidden_dim, 1)),
nn.Softplus(), # Physical conductance must be positive
)
def forward(self, inv_dx):
# We use log(1/dx) to linearize the scale of different geometries
log_inv_dx = torch.log(inv_dx + 1e-9)
return self.mlp(log_inv_dx)
class DiffusionLayer(MessagePassing):
@@ -13,28 +35,27 @@ class DiffusionLayer(MessagePassing):
channels: int,
**kwargs,
):
super().__init__(aggr="add", **kwargs)
self.dt = nn.Parameter(torch.tensor(1e-4))
self.conductivity_net = nn.Sequential(
nn.Linear(channels, channels, bias=False),
spectral_norm(nn.Linear(channels, channels, bias=False)),
nn.GELU(),
nn.Linear(channels, channels, bias=False),
spectral_norm(nn.Linear(channels, channels, bias=False)),
)
self.phys_encoder = nn.Sequential(
nn.Linear(1, 8, bias=False),
nn.Tanh(),
nn.Linear(8, 1, bias=False),
nn.Softplus(),
)
self.phys_encoder = LogPhysEncoder(hidden_dim=channels)
self.alpha_param = nn.Parameter(torch.tensor(1e-2))
@property
def alpha(self):
return torch.clamp(self.alpha_param, min=1e-7, max=1.0)
def forward(self, x, edge_index, edge_weight, conductivity):
edge_weight = edge_weight.unsqueeze(-1)
conductance = self.phys_encoder(edge_weight)
net_flux = self.propagate(edge_index, x=x, conductance=conductance)
return x + ((net_flux) * self.dt)
return x + self.alpha * net_flux
def message(self, x_i, x_j, conductance):
delta = x_j - x_i
@@ -44,15 +65,21 @@ class DiffusionLayer(MessagePassing):
class DiffusionNet(nn.Module):
def __init__(self, input_dim=1, output_dim=1, hidden_dim=8, n_layers=4):
def __init__(
self,
input_dim=1,
output_dim=1,
hidden_dim=8,
n_layers=4,
shared_weights=False,
):
super().__init__()
# Encoder: Projects input temperature to hidden feature space
self.enc = nn.Sequential(
nn.Linear(input_dim, hidden_dim, bias=True),
nn.GELU(),
nn.Linear(hidden_dim, hidden_dim, bias=True),
spectral_norm(nn.Linear(input_dim, hidden_dim, bias=True)),
nn.GELU(),
spectral_norm(nn.Linear(hidden_dim, hidden_dim, bias=True)),
)
self.scale_x = nn.Parameter(torch.zeros(hidden_dim))
@@ -60,27 +87,40 @@ class DiffusionNet(nn.Module):
# Scale parameters for conditioning
self.scale_edge_attr = nn.Parameter(torch.zeros(1))
# Stack of Diffusion Layers
self.layers = torch.nn.ModuleList(
[DiffusionLayer(hidden_dim) for _ in range(n_layers)]
)
# If shared_weights is True, use the same DiffusionLayer multiple times
if shared_weights:
diffusion_layer = DiffusionLayer(hidden_dim)
self.layers = torch.nn.ModuleList(
[diffusion_layer for _ in range(n_layers)]
)
# If shared_weights is False, use separate DiffusionLayers
else:
# Stack of Diffusion Layers
self.layers = torch.nn.ModuleList(
[DiffusionLayer(hidden_dim) for _ in range(n_layers)]
)
# Decoder: Projects hidden features back to Temperature space
self.dec = nn.Sequential(
nn.Linear(hidden_dim, hidden_dim, bias=True),
spectral_norm(nn.Linear(hidden_dim, hidden_dim, bias=True)),
nn.GELU(),
nn.Linear(hidden_dim, output_dim, bias=True),
spectral_norm(nn.Linear(hidden_dim, output_dim, bias=True)),
nn.Softplus(), # Ensure positive temperature output
)
self.func = torch.nn.GELU()
self.dt_param = nn.Parameter(torch.tensor(1e-2))
@property
def dt(self):
return torch.clamp(self.dt_param, min=1e-5, max=0.5)
def forward(self, x, edge_index, edge_attr, conductivity):
# 1. Global Residual Connection setup
# We save the input to add it back at the very end.
# The network learns the correction (Delta T), not the absolute T.
x_input = x
# 2. Encode
h = self.enc(x) * torch.exp(self.scale_x)
@@ -98,5 +138,5 @@ class DiffusionNet(nn.Module):
# 6. Final Update (Explicit Euler Step)
# T_new = T_old + Correction
# return x_input + delta_x
return delta_x
return delta_x + x_input * self.dt
# return delta_x

View File

@@ -0,0 +1,104 @@
import torch
from lightning.pytorch.callbacks import Callback
import os
class SwitchDataLoaderCallback(Callback):
def __init__(
self,
ckpt_path,
increase_unrolling_steps_by,
increase_unrolling_steps_every,
max_unrolling_steps=10,
patience=None,
last_patience=None,
metric="val/loss",
):
super().__init__()
self.ckpt_path = ckpt_path
if os.path.exists(ckpt_path) is False:
os.makedirs(ckpt_path)
self.increase_unrolling_steps_by = increase_unrolling_steps_by
self.increase_unrolling_steps_every = increase_unrolling_steps_every
self.max_unrolling_steps = max_unrolling_steps
self.metric = metric
self.actual_loss = torch.inf
if patience is not None:
self.patience = patience
if last_patience is not None:
self.last_patience = last_patience
self.no_improvement_epochs = 0
self.last_step_reached = False
def on_validation_epoch_end(self, trainer, pl_module):
self._metric_tracker(trainer, pl_module)
if self.last_step_reached is False:
self._unrolling_steps_handler(pl_module, trainer)
else:
if self.no_improvement_epochs >= self.last_patience:
trainer.should_stop = True
def _metric_tracker(self, trainer, pl_module):
if trainer.callback_metrics.get(self.metric) < self.actual_loss:
self.actual_loss = trainer.callback_metrics.get(self.metric)
self._save_model(pl_module, trainer)
self.no_improvement_epochs = 0
print(f"\nNew best {self.metric}: {self.actual_loss:.4f}")
else:
self.no_improvement_epochs += 1
print(
f"\nNo improvement in {self.metric} for {self.no_improvement_epochs} epochs."
)
def _should_reload_dataloader(self, trainer):
if self.patience is not None:
print(
f"Checking patience: {self.no_improvement_epochs} / {self.patience}"
)
if self.no_improvement_epochs >= self.patience:
return True
elif (
trainer.current_epoch + 1 % self.increase_unrolling_steps_every == 0
):
print("Reached scheduled epoch for increasing unrolling steps.")
return True
return False
def _unrolling_steps_handler(self, pl_module, trainer):
if self._should_reload_dataloader(trainer):
self._load_model(pl_module)
if pl_module.unrolling_steps >= self.max_unrolling_steps:
return
pl_module.unrolling_steps += self.increase_unrolling_steps_by
trainer.datamodule.unrolling_steps = pl_module.unrolling_steps
print(f"Incremented unrolling steps to {pl_module.unrolling_steps}")
trainer.datamodule.setup(stage="fit")
trainer.manual_dataloader_reload()
self.actual_loss = torch.inf
if pl_module.unrolling_steps >= self.max_unrolling_steps:
print(
"Reached max unrolling steps. Stopping further increments."
)
self.last_step_reached = True
def _save_model(self, pl_module, trainer):
pt_path = os.path.join(
self.ckpt_path,
f"{pl_module.unrolling_steps}_unrolling_best_model.pt",
)
torch.save(pl_module.state_dict(), pt_path) # <--- CHANGED THIS
ckpt_path = os.path.join(
self.ckpt_path,
f"{pl_module.unrolling_steps}_unrolling_best_checkpoint.ckpt",
)
trainer.save_checkpoint(ckpt_path, weights_only=False)
def _load_model(self, pl_module):
pt_path = os.path.join(
self.ckpt_path,
f"{pl_module.unrolling_steps}_unrolling_best_model.pt",
)
pl_module.load_state_dict(torch.load(pt_path, weights_only=True))
print(
f"Loaded model weights from {pt_path} for unrolling steps = {pl_module.unrolling_steps}"
)

View File

@@ -0,0 +1,72 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.adaptive_refined"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.adaptive_refined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "3_stripes.basic.1_adaptive_refined"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -10,30 +10,25 @@ trainer:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "5_step_4_layers_8_hidden"
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.adaptive_refined.combined"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
dirpath: logs.autoregressive.wandb/5_step_4_layers_8_hidden_0.7_radius/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
filename: best-checkpoint
- class_path: lightning.pytorch.callbacks.EarlyStopping
init_args:
monitor: val/loss
mode: min
patience: 10
verbose: false
increase_unrolling_steps_by: 4
patience: 5
last_patience: 10
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.adaptive_refined.combined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
@@ -41,22 +36,28 @@ model:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 8
hidden_dim: 16
output_dim: 1
n_layers: 4
unrolling_steps: 5
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 32
split_name:
- "4_stripes.basic.1_adaptive_refined"
- "3_stripes.basic.1_adaptive_refined"
- "2_stripes.basic.1_adaptive_refined"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null
lr_scheduler: null

View File

@@ -0,0 +1,72 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.refined"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.refined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "3_stripes.basic.refined"
n_elements: 50
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -0,0 +1,77 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.refined.combined"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 10
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.refined.combined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 10
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name:
- "4_stripes.basic.refined"
- "3_stripes.basic.refined"
- "2_stripes.basic.refined"
n_elements: 75
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 10
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null
ckpt_path: logs.autoregressive.wandb/10_steps/basic.refined.combined/16_layer_16_hidden/6_unrolling_best_checkpoint.ckpt

View File

@@ -0,0 +1,72 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.refined.star"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.refined.star/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "3_stripes.star"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -0,0 +1,72 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.star"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.star/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "3_stripes.star.refined"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -0,0 +1,75 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "16_layer_16_hidden.star.combined"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.star.combined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name:
- "4_stripes.star"
- "3_stripes.star"
- "2_stripes.star"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -0,0 +1,72 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady-10.steps"
name: "8_layer_16_hidden.star"
callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
- class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
init_args:
increase_unrolling_steps_by: 4
patience: 5
last_patience: 15
max_unrolling_steps: 10
ckpt_path: logs.autoregressive.wandb/10_steps/basic.star/8_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 8
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "3_stripes.star.refined"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
min_normalized_diff: 1e-4
optimizer: null
lr_scheduler: null

View File

@@ -0,0 +1,76 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: cpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
# logger:
# - class_path: lightning.pytorch.loggers.WandbLogger
# init_args:
# save_dir: logs.autoregressive.wandb
# project: "thermal-conduction-unsteady-10.steps"
# name: "16_layer_16_hidden.adaptive_refined.combined"
# callbacks:
# - class_path: lightning.pytorch.callbacks.ModelCheckpoint
# init_args:
# dirpath: logs.autoregressive.wandb/16_refined.10_steps/checkpoints
# monitor: val/loss
# mode: min
# save_top_k: 1
# filename: best-checkpoint
# - class_path: lightning.pytorch.callbacks.EarlyStopping
# init_args:
# monitor: val/loss
# mode: min
# patience: 30
# verbose: false
# - class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
# init_args:
# increase_unrolling_steps_by: 4
# patience: 15
# last_patience: 20
# max_unrolling_steps: 10
# ckpt_path: logs.autoregressive.wandb/10_steps/basic.adaptive_refined.combined/16_layer_16_hidden/
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 16
unrolling_steps: 2
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name:
# - "2_stripes.basic.refined"
# - "3_stripes.basic.refined"
# - "4_stripes.basic.1_adaptive_refined"
- "3_stripes.star"
n_elements: 50
batch_size: 32
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
unrolling_steps: 2
optimizer: null
lr_scheduler: null
ckpt_path: /home/folivo/storage/thermal-conduction-ml/logs.autoregressive.wandb/10_steps/basic.star.combined/16_layer_16_hidden/10_unrolling_best_checkpoint.ckpt

View File

@@ -10,8 +10,8 @@ trainer:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "16_refined"
project: "thermal-conduction-unsteady-5.steps"
name: "16_layer_16_hidden"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
@@ -24,16 +24,24 @@ trainer:
init_args:
monitor: val/loss
mode: min
patience: 10
patience: 30
verbose: false
# - class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
# init_args:
# increase_unrolling_steps_by: 5
# patience: 10
# last_patience: 15
# max_unrolling_steps: 20
# ckpt_path: logs.autoregressive.wandb/16_16_refined/checkpoints
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
accumulate_grad_batches: 4
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
@@ -45,18 +53,19 @@ model:
output_dim: 1
n_layers: 16
unrolling_steps: 5
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 8
split_name: "basic.refined"
n_elements: 100
batch_size: 32
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
unrolling_steps: 5
optimizer: null
lr_scheduler: null

View File

@@ -10,12 +10,12 @@ trainer:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "standard"
project: "thermal-conduction-unsteady-5.steps"
name: "32_layer_16_hidden"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
dirpath: logs.autoregressive.wandb/standard/checkpoints
dirpath: logs.autoregressive.wandb/32_refined/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
@@ -24,16 +24,24 @@ trainer:
init_args:
monitor: val/loss
mode: min
patience: 10
patience: 30
verbose: false
# - class_path: ThermalSolver.switch_dataloader_callback.SwitchDataLoaderCallback
# init_args:
# increase_unrolling_steps_by: 5
# patience: 10
# last_patience: 15
# max_unrolling_steps: 20
# ckpt_path: logs.autoregressive.wandb/16_16_refined/checkpoints
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
log_every_n_steps: 0
accumulate_grad_batches: 1
default_root_dir: null
gradient_clip_val: 1.0
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
@@ -41,22 +49,23 @@ model:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 8
hidden_dim: 16
output_dim: 1
n_layers: 8
n_layers: 32
unrolling_steps: 5
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 32
split_name: "basic.refined"
n_elements: 100
batch_size: 24
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
unrolling_steps: 5
optimizer: null
lr_scheduler: null

View File

@@ -10,12 +10,12 @@ trainer:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "refined"
project: "thermal-conduction-unsteady-5.steps"
name: "8_layer_16_hidden"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
dirpath: logs.autoregressive.wandb/refined/checkpoints
dirpath: logs.autoregressive.wandb/8_refined/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
@@ -24,7 +24,7 @@ trainer:
init_args:
monitor: val/loss
mode: min
patience: 10
patience: 30
verbose: false
max_epochs: 1000
min_epochs: null
@@ -32,7 +32,7 @@ trainer:
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
accumulate_grad_batches: 2
accumulate_grad_batches: 1
default_root_dir: null
model:
@@ -50,13 +50,14 @@ data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 16
split_name: "basic.refined"
n_elements: 100
batch_size: 32
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
unrolling_steps: 5
optimizer: null
lr_scheduler: null

View File

@@ -1,62 +0,0 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "16_8_refined"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
dirpath: logs.autoregressive.wandb/16_8_refined/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
filename: best-checkpoint
- class_path: lightning.pytorch.callbacks.EarlyStopping
init_args:
monitor: val/loss
mode: min
patience: 10
verbose: false
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
accumulate_grad_batches: 2
default_root_dir: null
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 8
output_dim: 1
n_layers: 16
unrolling_steps: 5
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 16
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
optimizer: null
lr_scheduler: null

View File

@@ -1,64 +0,0 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb/wandb
project: "thermal-conduction-unsteady"
name: "5_step_4_layers_16_hidden"
# retain: true
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
dirpath: logs.autoregressive.wandb/5_step_4_layers_16_hidden/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
filename: best-checkpoint
- class_path: lightning.pytorch.callbacks.EarlyStopping
init_args:
monitor: val/loss
mode: min
patience: 10
verbose: false
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
accumulate_grad_batches: 2
default_root_dir: null
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 4
unrolling_steps: 5
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy_refined"
batch_size: 32
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: true
radius: 0.5
remove_boundary_edges: true
start_unrolling_steps: 5
optimizer: null
lr_scheduler: null

View File

@@ -1,62 +0,0 @@
# lightning.pytorch==2.5.5
seed_everything: 1999
trainer:
accelerator: gpu
strategy: auto
devices: 1
num_nodes: 1
precision: null
logger:
- class_path: lightning.pytorch.loggers.WandbLogger
init_args:
save_dir: logs.autoregressive.wandb
project: "thermal-conduction-unsteady"
name: "standard"
callbacks:
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
init_args:
dirpath: logs.autoregressive.wandb/standard/checkpoints
monitor: val/loss
mode: min
save_top_k: 1
filename: best-checkpoint
- class_path: lightning.pytorch.callbacks.EarlyStopping
init_args:
monitor: val/loss
mode: min
patience: 10
verbose: false
max_epochs: 1000
min_epochs: null
max_steps: -1
min_steps: null
overfit_batches: 0.0
log_every_n_steps: null
accumulate_grad_batches: 2
default_root_dir: null
model:
class_path: ThermalSolver.autoregressive_module.GraphSolver
init_args:
model_class_path: ThermalSolver.model.diffusion_net.DiffusionNet
model_init_args:
input_dim: 1
hidden_dim: 16
output_dim: 1
n_layers: 8
unrolling_steps: 5
data:
class_path: ThermalSolver.graph_datamodule_unsteady.GraphDataModule
init_args:
hf_repo: "SISSAmathLab/thermal-conduction-unsteady"
split_name: "100_samples_easy"
batch_size: 16
train_size: 0.7
val_size: 0.2
test_size: 0.1
build_radial_graph: false
remove_boundary_edges: true
start_unrolling_steps: 5
optimizer: null
lr_scheduler: null

6
run.py
View File

@@ -5,7 +5,11 @@ torch.set_float32_matmul_precision("medium")
def main():
LightningCLI(subclass_mode_data=True, subclass_mode_model=True)
LightningCLI(
subclass_mode_data=True,
subclass_mode_model=True,
save_config_kwargs={"overwrite": True},
)
if __name__ == "__main__":

View File

@@ -1,8 +1,5 @@
#!/bin/bash
# python run.py fit --config experiments/config_4_layer_8_hidden.yaml
# python run.py fit --config experiments/config_8_layer_8_hidden.yaml
python run.py fit --config experiments/config_8_layer_16_hidden_refined.yaml
python run.py fit --config experiments/config_16_layer_8_hidden_refined.yaml
python run.py fit --config experiments/config_16_layer_16_hidden_refined.yaml
python run.py fit --config experiments/config_8_layer_16_hidden.yaml
# python run.py fit --config experiments/config_4_layer_16_hidden.yaml
export CUDA_VISIBLE_DEVICES=1
python run.py fit --config experiments/5_steps/config_16_layer_16_hidden_refined.yaml
python run.py fit --config experiments/5_steps/config_32_layer_16_hidden_refined.yaml
python run.py fit --config experiments/5_steps/config_8_layer_16_hidden_refined.yaml