"""Train and evaluate constitutive-memory baselines for T2 multiaxial v2.""" from __future__ import annotations import argparse import json import math import random import time from dataclasses import dataclass from pathlib import Path import h5py import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import torch from torch import nn from torch.nn import functional as F ROOT = Path(__file__).resolve().parents[1] DATA_ROOT = ROOT / "data" / "t2_multiaxial_ood_v2" ARTIFACT_ROOT = ROOT / "artifacts" / "t2_multiaxial_ood_v2" MODEL_ROOT = ROOT / "models" / "t2_multiaxial_ood_v2" PROTOCOLS = { "id": "split_id", "path_ood": "split_path_ood", "parameter_ood": "split_parameter_ood", } MODEL_NAMES = ("pointwise_mlp", "gru", "lstm", "causal_tcn", "physics_state_gru") PARAMETER_NAMES = ( "young_pa", "poisson", "yield_stress_pa", "hardening_modulus_pa", "backstress_c1_pa", "backstress_gamma1", "backstress_c2_pa", "backstress_gamma2", "isotropic_saturation_pa", "isotropic_rate", ) @dataclass class DatasetBundle: ids: list[str] material_models: list[str] path_families: list[str] splits: dict[str, list[str]] strain: torch.Tensor stress: torch.Tensor plastic_strain: torch.Tensor peeq: torch.Tensor backstress: torch.Tensor plastic_increment: torch.Tensor parameters: torch.Tensor def _resolve_shard(relative_path: str) -> Path: path = ROOT / relative_path if path.exists(): return path fallback = DATA_ROOT / "shards" / Path(relative_path).name if fallback.exists(): return fallback raise FileNotFoundError(relative_path) def load_dataset() -> DatasetBundle: manifest = json.loads((DATA_ROOT / "manifest.json").read_text(encoding="utf-8")) ids: list[str] = [] models: list[str] = [] families: list[str] = [] splits = {field: [] for field in PROTOCOLS.values()} strain = [] stress = [] plastic = [] peeq = [] backstress = [] plastic_increment = [] parameters = [] for shard in manifest["shards"]: with h5py.File(_resolve_shard(shard["path"]), "r") as h5: for sample_id in sorted(h5.keys()): group = h5[sample_id] ids.append(sample_id) models.append(str(group.attrs["material_model"])) families.append(str(group.attrs["path_family"])) for field in splits: splits[field].append(str(group.attrs[field])) strain.append(group["total_strain_voigt"][:].astype(np.float32)) stress.append(group["stress_voigt_pa"][:].astype(np.float32)) plastic.append(group["plastic_strain_voigt"][:].astype(np.float32)) peeq.append(group["equivalent_plastic_strain"][:].astype(np.float32)) backstress.append(group["backstress_voigt_pa"][:].astype(np.float32)) plastic_increment.append(group["plastic_multiplier_increment"][:].astype(np.float32)) parameters.append(group["material_parameter_vector"][:].astype(np.float32)) return DatasetBundle( ids=ids, material_models=models, path_families=families, splits=splits, strain=torch.from_numpy(np.stack(strain)), stress=torch.from_numpy(np.stack(stress)), plastic_strain=torch.from_numpy(np.stack(plastic)), peeq=torch.from_numpy(np.stack(peeq)), backstress=torch.from_numpy(np.stack(backstress)), plastic_increment=torch.from_numpy(np.stack(plastic_increment)), parameters=torch.from_numpy(np.stack(parameters)), ) def _safe_mean_std(value: torch.Tensor, dimensions: tuple[int, ...]) -> tuple[torch.Tensor, torch.Tensor]: mean = value.mean(dim=dimensions, keepdim=True) std = value.std(dim=dimensions, keepdim=True) std = torch.where(std < 1.0e-12, torch.ones_like(std), std) return mean, std def masks(bundle: DatasetBundle, split_field: str) -> dict[str, torch.Tensor]: values = bundle.splits[split_field] return { split: torch.tensor([value == split for value in values], dtype=torch.bool) for split in ("train", "validation", "test") } def model_indicator(bundle: DatasetBundle) -> torch.Tensor: return torch.tensor( [[1.0, 0.0] if name == "j2_linear_isotropic" else [0.0, 1.0] for name in bundle.material_models], dtype=torch.float32, ) @dataclass class Normalization: strain_mean: torch.Tensor strain_std: torch.Tensor parameter_mean: torch.Tensor parameter_std: torch.Tensor stress_mean: torch.Tensor stress_std: torch.Tensor plastic_scale: torch.Tensor backstress_scale: torch.Tensor peeq_scale: torch.Tensor def json_dict(self) -> dict[str, object]: return {name: value.detach().cpu().numpy().reshape(-1).tolist() for name, value in vars(self).items()} def fit_normalization(bundle: DatasetBundle, train_mask: torch.Tensor) -> Normalization: strain_mean, strain_std = _safe_mean_std(bundle.strain[train_mask], (0, 1)) parameter_mean, parameter_std = _safe_mean_std(bundle.parameters[train_mask], (0,)) stress_mean, stress_std = _safe_mean_std(bundle.stress[train_mask], (0, 1)) plastic_scale = bundle.plastic_strain[train_mask].abs().amax(dim=(0, 1), keepdim=True).clamp_min(1.0e-6) backstress_scale = bundle.backstress[train_mask].abs().amax(dim=(0, 1), keepdim=True).clamp_min(1.0e6) peeq_scale = bundle.peeq[train_mask].amax().reshape(1, 1).clamp_min(1.0e-5) return Normalization(strain_mean, strain_std, parameter_mean, parameter_std, stress_mean, stress_std, plastic_scale, backstress_scale, peeq_scale) def normalized_inputs(bundle: DatasetBundle, norm: Normalization) -> torch.Tensor: strain = (bundle.strain - norm.strain_mean) / norm.strain_std parameters = (bundle.parameters - norm.parameter_mean) / norm.parameter_std repeated = parameters[:, None, :].expand(-1, strain.shape[1], -1) indicator = model_indicator(bundle)[:, None, :].expand(-1, strain.shape[1], -1) return torch.cat((strain, repeated, indicator), dim=-1) class PointwiseMLP(nn.Module): def __init__(self, input_size: int, hidden: int = 96): super().__init__() self.network = nn.Sequential( nn.Linear(input_size, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(), nn.Linear(hidden, 6), ) def forward(self, value: torch.Tensor) -> torch.Tensor: return self.network(value) class RecurrentStress(nn.Module): def __init__(self, input_size: int, *, cell: str, hidden: int = 72): super().__init__() recurrent = nn.GRU if cell == "gru" else nn.LSTM self.recurrent = recurrent(input_size, hidden, num_layers=2, batch_first=True) self.output = nn.Linear(hidden, 6) def forward(self, value: torch.Tensor) -> torch.Tensor: hidden, _ = self.recurrent(value) return self.output(hidden) class CausalBlock(nn.Module): def __init__(self, width: int, dilation: int): super().__init__() self.padding = 2 * dilation self.conv = nn.Conv1d(width, width, kernel_size=3, dilation=dilation, padding=self.padding) self.norm = nn.GroupNorm(1, width) def forward(self, value: torch.Tensor) -> torch.Tensor: updated = self.conv(value) updated = updated[..., : value.shape[-1]] return F.silu(self.norm(updated)) + value class CausalTCN(nn.Module): def __init__(self, input_size: int, width: int = 72): super().__init__() self.input = nn.Conv1d(input_size, width, kernel_size=1) self.blocks = nn.Sequential(*(CausalBlock(width, dilation) for dilation in (1, 2, 4, 8))) self.output = nn.Conv1d(width, 6, kernel_size=1) def forward(self, value: torch.Tensor) -> torch.Tensor: sequence = value.transpose(1, 2) return self.output(self.blocks(self.input(sequence))).transpose(1, 2) def dev5_to_voigt(value: torch.Tensor) -> torch.Tensor: xx, yy, xy, yz, xz = value.unbind(dim=-1) return torch.stack((xx, yy, -xx - yy, xy, yz, xz), dim=-1) def hooke_stress(strain: torch.Tensor, plastic: torch.Tensor, parameters: torch.Tensor) -> torch.Tensor: elastic = strain - plastic young = parameters[:, None, 0] poisson = parameters[:, None, 1] shear = young / (2.0 * (1.0 + poisson)) bulk = young / (3.0 * (1.0 - 2.0 * poisson)) trace = elastic[..., 0] + elastic[..., 1] + elastic[..., 2] mean = trace / 3.0 normal = 2.0 * shear[..., None] * (elastic[..., :3] - mean[..., None]) + bulk[..., None] * trace[..., None] shear_stress = 2.0 * shear[..., None] * elastic[..., 3:] return torch.cat((normal, shear_stress), dim=-1) class PhysicsStateGRU(nn.Module): """Causal internal-state model with exact deviatoric PE and Hooke reconstruction.""" def __init__(self, input_size: int, hidden: int = 80): super().__init__() self.recurrent = nn.GRU(input_size, hidden, num_layers=2, batch_first=True) self.state_head = nn.Linear(hidden, 11) def forward( self, normalized_input: torch.Tensor, strain: torch.Tensor, parameters: torch.Tensor, norm: Normalization, ) -> dict[str, torch.Tensor]: hidden, _ = self.recurrent(normalized_input) raw = self.state_head(hidden) plastic5 = raw[..., :5] * norm.plastic_scale[..., (0, 1, 3, 4, 5)] backstress5 = raw[..., 5:10] * norm.backstress_scale[..., (0, 1, 3, 4, 5)] plastic = dev5_to_voigt(plastic5) backstress = dev5_to_voigt(backstress5) increments = ( F.softplus(raw[:, 1:, 10]) * norm.peeq_scale.squeeze() / max(raw.shape[1] - 1, 1) ) peeq = torch.cat( ( torch.zeros_like(raw[:, :1, 10]), torch.cumsum(increments, dim=1), ), dim=1, ) stress = hooke_stress(strain, plastic, parameters) return {"stress": stress, "plastic_strain": plastic, "backstress": backstress, "peeq": peeq} def build_model(name: str, input_size: int) -> nn.Module: if name == "pointwise_mlp": return PointwiseMLP(input_size) if name == "gru": return RecurrentStress(input_size, cell="gru") if name == "lstm": return RecurrentStress(input_size, cell="lstm") if name == "causal_tcn": return CausalTCN(input_size) if name == "physics_state_gru": return PhysicsStateGRU(input_size) raise ValueError(name) def voigt_mises(stress: torch.Tensor) -> torch.Tensor: mean = stress[..., :3].mean(dim=-1, keepdim=True) dev_normal = stress[..., :3] - mean square = (dev_normal**2).sum(dim=-1) + 2.0 * (stress[..., 3:] ** 2).sum(dim=-1) return torch.sqrt(torch.clamp(1.5 * square, min=0.0)) def predict(model: nn.Module, name: str, x: torch.Tensor, bundle: DatasetBundle, indices: torch.Tensor, norm: Normalization) -> dict[str, torch.Tensor]: if name == "physics_state_gru": return model(x[indices], bundle.strain[indices], bundle.parameters[indices], norm) normalized = model(x[indices]) return {"stress": normalized * norm.stress_std + norm.stress_mean} def physics_loss(predicted: dict[str, torch.Tensor], bundle: DatasetBundle, indices: torch.Tensor, norm: Normalization) -> torch.Tensor: target_stress = bundle.stress[indices] target_plastic = bundle.plastic_strain[indices] target_backstress = bundle.backstress[indices] target_peeq = bundle.peeq[indices] stress_loss = (((predicted["stress"] - target_stress) / norm.stress_std) ** 2).mean() plastic_loss = (((predicted["plastic_strain"] - target_plastic) / norm.plastic_scale) ** 2).mean() backstress_loss = (((predicted["backstress"] - target_backstress) / norm.backstress_scale) ** 2).mean() peeq_loss = (((predicted["peeq"] - target_peeq) / norm.peeq_scale) ** 2).mean() monotonic = ( F.relu(predicted["peeq"][:, :-1] - predicted["peeq"][:, 1:]).mean() / norm.peeq_scale.squeeze() ) parameters = bundle.parameters[indices] chaboche = model_indicator(bundle)[indices, 1][:, None] j2_radius = ( parameters[:, 2][:, None] + parameters[:, 3][:, None] * predicted["peeq"] ) chaboche_radius = parameters[:, 2][:, None] + parameters[:, 8][:, None] * ( 1.0 - torch.exp(-parameters[:, 9][:, None] * predicted["peeq"]) ) radius = (1.0 - chaboche) * j2_radius + chaboche * chaboche_radius shifted_mises = voigt_mises(predicted["stress"] - predicted["backstress"]) plastic_mask = bundle.plastic_increment[indices] > 0.0 yield_loss = ( ((shifted_mises - radius) / radius.clamp_min(1.0))[plastic_mask] ** 2 ).mean() return ( stress_loss + 0.25 * plastic_loss + 0.08 * backstress_loss + 0.10 * peeq_loss + 0.05 * monotonic + 0.10 * yield_loss ) def train_one( name: str, bundle: DatasetBundle, split_mask: dict[str, torch.Tensor], norm: Normalization, *, epochs: int, batch_size: int, seed: int, ) -> tuple[nn.Module, list[dict[str, float]]]: torch.manual_seed(seed) random.seed(seed) x = normalized_inputs(bundle, norm) model = build_model(name, x.shape[-1]) optimizer = torch.optim.AdamW(model.parameters(), lr=2.0e-3, weight_decay=1.0e-5) train_indices = torch.where(split_mask["train"])[0] validation_indices = torch.where(split_mask["validation"])[0] best_state = None best_validation = math.inf stale = 0 history: list[dict[str, float]] = [] for epoch in range(epochs): model.train() order = train_indices[torch.randperm(len(train_indices))] losses = [] for start in range(0, len(order), batch_size): index = order[start : start + batch_size] optimizer.zero_grad(set_to_none=True) if name == "physics_state_gru": predicted = predict(model, name, x, bundle, index, norm) loss = physics_loss(predicted, bundle, index, norm) else: output = model(x[index]) target = (bundle.stress[index] - norm.stress_mean) / norm.stress_std loss = F.mse_loss(output, target) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() losses.append(float(loss.detach())) model.eval() with torch.no_grad(): if name == "physics_state_gru": validation = float(physics_loss(predict(model, name, x, bundle, validation_indices, norm), bundle, validation_indices, norm)) else: validation = float(F.mse_loss(model(x[validation_indices]), (bundle.stress[validation_indices] - norm.stress_mean) / norm.stress_std)) history.append({"epoch": epoch + 1, "train_loss": float(np.mean(losses)), "validation_loss": validation}) if validation < best_validation - 1.0e-6: best_validation = validation best_state = {key: value.detach().clone() for key, value in model.state_dict().items()} stale = 0 else: stale += 1 if stale >= 8 and epoch >= 14: break if best_state is None: raise RuntimeError("Training did not produce a checkpoint.") model.load_state_dict(best_state) return model, history def _double_contract(stress: torch.Tensor, strain_increment: torch.Tensor) -> torch.Tensor: weights = torch.tensor((1.0, 1.0, 1.0, 2.0, 2.0, 2.0), dtype=stress.dtype) return (stress * strain_increment * weights).sum(dim=-1) def evaluate( model: nn.Module, name: str, bundle: DatasetBundle, selected: torch.Tensor, norm: Normalization, ) -> tuple[dict[str, float], dict[str, torch.Tensor]]: x = normalized_inputs(bundle, norm) indices = torch.where(selected)[0] model.eval() started = time.perf_counter() with torch.no_grad(): predicted = predict(model, name, x, bundle, indices, norm) elapsed = time.perf_counter() - started reference = bundle.stress[indices] error = predicted["stress"] - reference rmse = torch.sqrt((error**2).mean()) mae = error.abs().mean() centered = reference - reference.mean() r2 = 1.0 - (error**2).sum() / (centered**2).sum().clamp_min(1.0) predicted_mises = voigt_mises(predicted["stress"]) reference_mises = voigt_mises(reference) peak_error = ((predicted_mises.amax(dim=1) - reference_mises.amax(dim=1)).abs() / reference_mises.amax(dim=1).clamp_min(1.0)).mean() increments = bundle.strain[indices, 1:] - bundle.strain[indices, :-1] predicted_work = _double_contract(0.5 * (predicted["stress"][:, 1:] + predicted["stress"][:, :-1]), increments).sum(dim=1) reference_work = _double_contract(0.5 * (reference[:, 1:] + reference[:, :-1]), increments).sum(dim=1) work_error = ((predicted_work - reference_work).abs() / reference_work.abs().clamp_min(1.0)).mean() alpha = bundle.backstress[indices] shifted = predicted["stress"] - alpha shifted_mises = voigt_mises(shifted) params = bundle.parameters[indices] peeq = bundle.peeq[indices] indicator = model_indicator(bundle)[indices, 1][:, None] j2_radius = params[:, 2][:, None] + params[:, 3][:, None] * peeq chaboche_radius = params[:, 2][:, None] + params[:, 8][:, None] * (1.0 - torch.exp(-params[:, 9][:, None] * peeq)) radius = (1.0 - indicator) * j2_radius + indicator * chaboche_radius plastic_mask = bundle.plastic_increment[indices] > 0.0 yield_residual = ((shifted_mises - radius).abs() / radius.clamp_min(1.0))[plastic_mask].mean() decimated = torch.arange(0, bundle.strain.shape[1], 2) if decimated[-1] != bundle.strain.shape[1] - 1: decimated = torch.cat((decimated, torch.tensor([bundle.strain.shape[1] - 1]))) with torch.no_grad(): if name == "physics_state_gru": coarse = model(x[indices][:, decimated], bundle.strain[indices][:, decimated], bundle.parameters[indices], norm)["stress"] else: coarse = model(x[indices][:, decimated]) * norm.stress_std + norm.stress_mean resolution_rmse = torch.sqrt(((coarse - reference[:, decimated]) ** 2).mean()) metrics = { "rmse_mpa": float(rmse / 1.0e6), "mae_mpa": float(mae / 1.0e6), "r2": float(r2), "mean_peak_mises_relative_error": float(peak_error), "mean_work_relative_error": float(work_error), "mean_yield_surface_relative_residual_using_reference_state": float(yield_residual), "decimated_121_state_rmse_mpa": float(resolution_rmse / 1.0e6), "inference_seconds": elapsed, "trajectory_count": int(len(indices)), } if name == "physics_state_gru": peeq_predicted = predicted["peeq"] metrics.update( plastic_strain_rmse=float(torch.sqrt(((predicted["plastic_strain"] - bundle.plastic_strain[indices]) ** 2).mean())), backstress_rmse_mpa=float(torch.sqrt(((predicted["backstress"] - bundle.backstress[indices]) ** 2).mean()) / 1.0e6), peeq_rmse=float(torch.sqrt(((peeq_predicted - bundle.peeq[indices]) ** 2).mean())), peeq_nonmonotone_fraction=float((peeq_predicted[:, 1:] < peeq_predicted[:, :-1]).float().mean()), maximum_plastic_strain_trace=float((predicted["plastic_strain"][..., :3].sum(dim=-1)).abs().max()), ) return metrics, {**predicted, "indices": indices} def _write_json(path: Path, value: object) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8") def train_suite( *, epochs: int = 35, batch_size: int = 32, seed: int = 20261001, protocols: tuple[str, ...] = tuple(PROTOCOLS), model_names: tuple[str, ...] = MODEL_NAMES, ) -> dict[str, object]: torch.set_num_threads(min(8, max(1, torch.get_num_threads()))) bundle = load_dataset() ARTIFACT_ROOT.mkdir(parents=True, exist_ok=True) MODEL_ROOT.mkdir(parents=True, exist_ok=True) metrics_path = ARTIFACT_ROOT / "model_metrics.json" all_metrics: dict[str, object] = ( json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else {} ) representative: dict[tuple[str, str], tuple[dict[str, torch.Tensor], torch.Tensor]] = {} started = time.perf_counter() for protocol_index, protocol in enumerate(protocols): split_field = PROTOCOLS[protocol] split_mask = masks(bundle, split_field) norm = fit_normalization(bundle, split_mask["train"]) _write_json(MODEL_ROOT / f"{protocol}_normalization.json", {"protocol": protocol, "split_field": split_field, "parameter_names": PARAMETER_NAMES, "normalization": norm.json_dict()}) for model_index, name in enumerate(model_names): print(f"training {protocol}/{name}", flush=True) model, history = train_one(name, bundle, split_mask, norm, epochs=epochs, batch_size=batch_size, seed=seed + 100 * protocol_index + model_index) metrics, prediction = evaluate(model, name, bundle, split_mask["test"], norm) parameter_count = sum(value.numel() for value in model.parameters()) metrics["parameter_count"] = parameter_count metrics["epochs_completed"] = len(history) metrics["best_validation_loss"] = min(item["validation_loss"] for item in history) all_metrics.setdefault(protocol, {})[name] = metrics checkpoint = { "model_name": name, "protocol": protocol, "split_field": split_field, "input_size": int(normalized_inputs(bundle, norm).shape[-1]), "parameter_count": parameter_count, "state_dict": model.state_dict(), "normalization": norm.json_dict(), "parameter_names": PARAMETER_NAMES, "voigt_order": ("xx", "yy", "zz", "xy", "yz", "xz"), "strain_shear_convention": "tensor", "seed": seed + 100 * protocol_index + model_index, } torch.save(checkpoint, MODEL_ROOT / f"{protocol}_{name}.pt") _write_json(MODEL_ROOT / f"{protocol}_{name}_history.json", history) if protocol in {"id", "path_ood"} and name in {"gru", "physics_state_gru"}: representative[(protocol, name)] = (prediction, bundle.stress[prediction["indices"]]) print(json.dumps({"protocol": protocol, "model": name, **metrics}, sort_keys=True), flush=True) _write_json(ARTIFACT_ROOT / "model_metrics.json", all_metrics) figure, axes = plt.subplots(1, 3, figsize=(13.5, 4.2), constrained_layout=True) for axis, protocol in zip(axes, PROTOCOLS, strict=True): values = [all_metrics[protocol][name]["rmse_mpa"] for name in MODEL_NAMES] axis.bar(range(len(values)), values, color=("#9ca3af", "#2563eb", "#7c3aed", "#0f766e", "#dc2626")) axis.set_xticks(range(len(values)), ("MLP", "GRU", "LSTM", "TCN", "Physics\nstate GRU"), rotation=25, ha="right") axis.set_ylabel("Stress RMSE (MPa)") axis.set_title(protocol.replace("_", " ").upper()) axis.grid(axis="y", alpha=0.2) figure.savefig(ARTIFACT_ROOT / "model_protocol_comparison.png", dpi=190) plt.close(figure) summary = { "status": "completed", "dataset_sample_count": len(bundle.ids), "protocols": protocols, "models": model_names, "epochs_requested": epochs, "batch_size": batch_size, "seed": seed, "elapsed_seconds": time.perf_counter() - started, "metrics_path": str((ARTIFACT_ROOT / "model_metrics.json").relative_to(ROOT)), "model_directory": str(MODEL_ROOT.relative_to(ROOT)), } _write_json(ARTIFACT_ROOT / "training_summary.json", summary) print(json.dumps(summary, indent=2), flush=True) return summary def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--epochs", type=int, default=35) parser.add_argument("--batch-size", type=int, default=32) parser.add_argument("--seed", type=int, default=20261001) parser.add_argument("--protocols", nargs="+", choices=tuple(PROTOCOLS), default=tuple(PROTOCOLS)) parser.add_argument("--models", nargs="+", choices=MODEL_NAMES, default=MODEL_NAMES) args = parser.parse_args() train_suite( epochs=args.epochs, batch_size=args.batch_size, seed=args.seed, protocols=tuple(args.protocols), model_names=tuple(args.models), ) if __name__ == "__main__": main()