Upload folder using huggingface_hub
Browse filesFiles changed (18)
- .gitattributes+25-10
- README.mdAdded+130
- conf/config.yamlAdded+58
- configuration.jsonAdded+1
- data/AC.matAdded+3
- model/__pycache__/fpinn.cpython-311.pycAdded
- model/fpinn.pyAdded+190
- result/fpinn_forward_history.npzAdded+3
- scripts/__pycache__/common.cpython-311.pycAdded
- scripts/__pycache__/data_utils.cpython-311.pycAdded
- scripts/__pycache__/inference.cpython-311.pycAdded
- scripts/__pycache__/train.cpython-311.pycAdded
- scripts/common.pyAdded+61
- scripts/data_utils.pyAdded+77
- scripts/inference.pyAdded+154
- scripts/train.pyAdded+223
- weight/.gitkeepAdded
- weight/fpinn_forward.ptAdded+3
12345567891011111214151314151620212217181925202128222331242526272829303132333435363738394041424344454647484950*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bin.* filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text *.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zstandard filter=lfs diff=lfs merge=lfs -text*.tfevents* filter=lfs diff=lfs merge=lfs -text*.db* filter=lfs diff=lfs merge=lfs -text*.ark* filter=lfs diff=lfs merge=lfs -text**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.gguf* filter=lfs diff=lfs merge=lfs -text*.ggml filter=lfs diff=lfs merge=lfs -text*.llamafile* filter=lfs diff=lfs merge=lfs -text*.pt2 filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text *.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -textdata/AC.mat filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130---frameworks: - pytorchlanguage: - enlicense: apache-2.0tags: - OneScience - FPINNs - fuzzy-physics-informed-neural-networks - Allen-Cahn - forward-problem - inverse-problemtasks: - pde-solving---<p align="center"> <strong> <span style="font-size: 30px;">FPINNs</span> </strong></p>
# Model Overview
In this model package, FPINNs refers to Fuzzy Physics-Informed Neural Networks, not fractional PINNs. The architecture augments a fully connected network with a Gaussian fuzzy-membership branch and fuses neural features with fuzzy-rule features to predict solutions to partial differential equations.
The current example solves the Allen–Cahn equation:
```textu_t - lambda_1 u_xx + lambda_2 (u^3 - u) = 0```
Paper: Deep fuzzy physics-informed neural networks for forward and inverse PDE problems https://doi.org/10.1016/j.neunet.2024.106750
# Model Description
FPINNs are trained jointly on data loss and PDE residuals and support both forward and inverse Allen–Cahn problems. The forward task predicts the spatiotemporal solution for known parameters `lambda_1=0.0001` and `lambda_2=5.0`; the inverse task jointly learns the equation solution and both parameters from observations. The model is trained with Adam by default, with optional L-BFGS refinement.
# Use Cases
| Use Case | Description || :---: | :--- || Forward Allen–Cahn problem | Predict the complete spatiotemporal solution using known diffusion and reaction parameters || Inverse Allen–Cahn problem | Identify diffusion and reaction parameters from solution observations || Fuzzy-feature research | Evaluate the fusion of neural features and Gaussian fuzzy-rule features || Pipeline validation | Validate training and inference using the bundled data and a small-scale configuration |
# Usage
## 1. OneCode
Use the online OneCode environment for an intelligent, one-click AI for Science (AI4S) programming experience:
[Launch OneCode for one-click AI4S programming](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
## 2. Manual Setup
**Hardware Requirements**
- A GPU or DCU is recommended for training and full-grid inference.- A CPU can be used for small-scale pipeline validation.- DCU users must install DTK and a PyTorch environment compatible with the target cluster.
### Download the Model Package
```bashhf download --model OneScience-Sugon/FPINNs --local-dir ./FPINNscd FPINNs```
### Set Up the Runtime Environment
**DCU Environment**
```bash# Activate DTK and Conda firstconda create -n onescience311 python=3.11 -yconda activate onescience311pip install onescience[cfd-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
**GPU Environment**
```bash# Activate Conda firstconda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12conda activate onescience311pip install onescience[cfd-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai```
### Training Data
The model package includes the Allen–Cahn data file `data/AC.mat`, which contains spatial coordinates, temporal coordinates, and the corresponding equation solution. The number of training samples and evaluation batch size can be adjusted in `conf/config.yaml`.
### Training
The training task is controlled by `common.task` in `conf/config.yaml`: `forward` selects the forward problem, while `inverse` selects the inverse problem. After configuring the task, run:
```bashpython scripts/train.py```
Training checkpoints and histories are saved to the `weight/` and `result/` directories by default.
### Model Weights
This repository provides weights trained on the Allen–Cahn dataset in the `weight/` directory.
### Inference, Evaluation, and Visualization
After training the selected task, run:
```bashpython scripts/inference.py```
The inference task is also controlled by `common.task`. Results are saved as `result/fpinn_forward.*` or `result/fpinn_inverse.*` by default. The inverse task additionally reports the recovered `lambda_1` and `lambda_2` values. Model, training, loss, and inference parameters can all be modified in `conf/config.yaml`.
# Official OneScience Resources
| Platform | OneScience Repository | Skills Repository || --- | --- | --- || Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills || GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
# Citations and License
- Wu, W., Duan, S., Sun, Y., Yu, Y., Liu, D., and Peng, D. Deep fuzzy physics-informed neural networks for forward and inverse PDE problems. Neural Networks, 181, 106750, 2025.- This model package is released under the Apache-2.0 license and retains attribution to the original paper and data sources.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758root: common: task: "forward" device: "auto" dtype: "float32" seed: 1111 weight_dir: "weight" result_dir: "result"
data: mat_file: "data/AC.mat" n_train: 8000 evaluation_batch_size: 8192
model: hidden_layers: [200, 200, 200, 200] linear_dim: 10 fuzzy_dim: 4 activation: "tanh"
tasks: forward: training: epochs: 10000 lr: 0.001 lbfgs_iters: 0 log_interval: 500 loss: data: 1.0 pde: 1.0 pde: lambda_1: 0.0001 lambda_2: 5.0 output: checkpoint_name: "fpinn_forward.pt" history_name: "fpinn_forward_history.npz" predictions_name: "fpinn_forward.npz" figure_name: "fpinn_forward.png"
inverse: training: epochs: 10000 lr: 0.001 lbfgs_iters: 0 log_interval: 500 loss: data: 1.0 pde: 1.0 pde: initial_lambda_1: 1.0 initial_lambda_2: 0.0 true_lambda_1: 0.0001 true_lambda_2: 5.0 output: checkpoint_name: "fpinn_inverse.pt" history_name: "fpinn_inverse_history.npz" predictions_name: "fpinn_inverse.npz" figure_name: "fpinn_inverse.png"1{"framework":"Pytorch","task":"other"}123version https://git-lfs.github.com/spec/v1oid sha256:266e97eedd9ef543d7f6d370fa5f06388761aa7da2b97e476562dcf1d644a175size 559196123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190from __future__ import annotations
from collections.abc import Mapping, Sequence
import torchimport torch.nn as nn
class FCN(nn.Module): """Fully connected trunk used by the fuzzy PINN."""
def __init__( self, layer_sizes: Sequence[int], activation: str = "tanh", dtype: torch.dtype = torch.float32, ) -> None: super().__init__() if len(layer_sizes) < 2: raise ValueError("layer_sizes must include input and output widths") if activation not in {"tanh", "sin", "sine", "relu", "gelu"}: raise ValueError(f"unsupported activation: {activation}") self.activation = "sin" if activation == "sine" else activation self.linears = nn.ModuleList( nn.Linear(layer_sizes[index], layer_sizes[index + 1], dtype=dtype) for index in range(len(layer_sizes) - 1) )
def _activate(self, values: torch.Tensor) -> torch.Tensor: if self.activation == "gelu": return torch.nn.functional.gelu(values) return getattr(torch, self.activation)(values)
def forward(self, inputs: torch.Tensor) -> torch.Tensor: hidden = inputs for linear in self.linears[:-1]: hidden = self._activate(linear(hidden)) return self.linears[-1](hidden)
class FuzzyLayer(nn.Module): """Gaussian fuzzy membership rules followed by product inference."""
def __init__( self, input_dim: int, rule_count: int, dtype: torch.dtype = torch.float32, ) -> None: super().__init__() if min(input_dim, rule_count) <= 0: raise ValueError("input_dim and rule_count must be positive") self.input_dim = input_dim self.rule_count = rule_count self.centers = nn.Parameter(torch.empty(rule_count, input_dim, dtype=dtype)) self.sigma = nn.Parameter(torch.ones(rule_count, input_dim, dtype=dtype)) nn.init.xavier_uniform_(self.centers)
def forward(self, inputs: torch.Tensor) -> torch.Tensor: differences = inputs[:, None, :] - self.centers[None, :, :] variance = self.sigma.square().clamp_min(torch.finfo(inputs.dtype).eps) memberships = torch.exp(-differences.square() / variance[None, :, :]) return memberships.prod(dim=-1)
class FPINNNet(nn.Module): """Parallel neural and fuzzy feature branches with a fused linear head."""
def __init__( self, hidden_layers: Sequence[int], linear_dim: int, fuzzy_dim: int, activation: str = "tanh", dtype: torch.dtype = torch.float32, ) -> None: super().__init__() self.fcn = FCN( [2, *hidden_layers, linear_dim], activation=activation, dtype=dtype ) self.fuzzy = FuzzyLayer(2, fuzzy_dim, dtype=dtype) self.head = nn.Linear(linear_dim + fuzzy_dim, 1, dtype=dtype)
def forward(self, coordinates: torch.Tensor) -> torch.Tensor: neural_features = torch.tanh(self.fcn(coordinates)) fuzzy_features = self.fuzzy(coordinates) return self.head(torch.cat((neural_features, fuzzy_features), dim=1))
class FPINNForward(nn.Module): """Forward Allen-Cahn solver with fixed PDE parameters."""
def __init__( self, model_config: Mapping, dtype: torch.dtype = torch.float32 ) -> None: super().__init__() self.net = FPINNNet( hidden_layers=model_config["hidden_layers"], linear_dim=int(model_config["linear_dim"]), fuzzy_dim=int(model_config["fuzzy_dim"]), activation=str(model_config["activation"]), dtype=dtype, )
def forward(self, coordinates: torch.Tensor) -> torch.Tensor: return self.net(coordinates)
def predict_u(self, coordinates: torch.Tensor) -> torch.Tensor: return self.forward(coordinates)
class FPINNInverse(FPINNForward): """Inverse Allen-Cahn solver with learnable diffusion and reaction values."""
def __init__( self, model_config: Mapping, initial_lambda_1: float = 1.0, initial_lambda_2: float = 0.0, dtype: torch.dtype = torch.float32, ) -> None: super().__init__(model_config, dtype=dtype) self.lambda_1 = nn.Parameter(torch.tensor(initial_lambda_1, dtype=dtype)) self.lambda_2 = nn.Parameter(torch.tensor(initial_lambda_2, dtype=dtype))
def build_model( task: str, model_config: Mapping, pde_config: Mapping, dtype: torch.dtype,) -> FPINNForward: if task == "forward": return FPINNForward(model_config, dtype=dtype) if task == "inverse": return FPINNInverse( model_config, initial_lambda_1=float(pde_config["initial_lambda_1"]), initial_lambda_2=float(pde_config["initial_lambda_2"]), dtype=dtype, ) raise ValueError(f"unsupported task: {task}")
def allen_cahn_residual( model: FPINNForward, coordinates: torch.Tensor, lambda_1: float | torch.Tensor, lambda_2: float | torch.Tensor,) -> torch.Tensor: inputs = coordinates.detach().requires_grad_(True) prediction = model(inputs) gradient = torch.autograd.grad( prediction, inputs, torch.ones_like(prediction), create_graph=True )[0] prediction_x = gradient[:, 0:1] prediction_t = gradient[:, 1:2] prediction_xx = torch.autograd.grad( prediction_x, inputs, torch.ones_like(prediction_x), create_graph=True, )[0][:, 0:1] return ( prediction_t - lambda_1 * prediction_xx + lambda_2 * (prediction.pow(3) - prediction) )
def loss_components( model: FPINNForward, x_data: torch.Tensor, u_data: torch.Tensor, x_pde: torch.Tensor, lambda_1: float | torch.Tensor, lambda_2: float | torch.Tensor,) -> dict[str, torch.Tensor]: prediction = model(x_data) residual = allen_cahn_residual(model, x_pde, lambda_1, lambda_2) return { "data": torch.mean((prediction - u_data).square()), "pde": torch.mean(residual.square()), }
def weighted_loss(components: Mapping[str, torch.Tensor], weights: Mapping) -> torch.Tensor: return float(weights["data"]) * components["data"] + float( weights["pde"] ) * components["pde"]123version https://git-lfs.github.com/spec/v1oid sha256:34c76c41ee404a6ef8baf3dbcb39585f5b2fc42f82fcdca5e9637f6297a86fb5size 4207812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from __future__ import annotations
import randomfrom collections.abc import Mappingfrom pathlib import Path
import numpy as npimport torchimport yaml
def load_config(path: Path) -> dict: with path.open("r", encoding="utf-8") as stream: config = yaml.safe_load(stream) if not isinstance(config, dict) or "root" not in config: raise ValueError(f"config must contain a 'root' mapping: {path}") return config["root"]
def project_path(value: str | Path, project_root: Path) -> Path: path = Path(value).expanduser() return path if path.is_absolute() else project_root / path
def resolve_device(requested: str) -> torch.device: if requested == "auto": return torch.device("cuda" if torch.cuda.is_available() else "cpu") device = torch.device(requested) if device.type == "cuda" and not torch.cuda.is_available(): raise RuntimeError("CUDA/DCU was requested but torch.cuda.is_available() is false") return device
def resolve_dtype(name: str) -> torch.dtype: try: return {"float32": torch.float32, "float64": torch.float64}[name] except KeyError as error: raise ValueError(f"unsupported dtype: {name}") from error
def seed_everything(seed: int) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
def relative_l2(prediction: np.ndarray, reference: np.ndarray) -> float: return float( np.linalg.norm(prediction.reshape(-1) - reference.reshape(-1)) / (np.linalg.norm(reference.reshape(-1)) + 1.0e-12) )
def checkpoint_state(checkpoint: Mapping) -> tuple[Mapping[str, torch.Tensor], dict]: if "model_state" in checkpoint: return checkpoint["model_state"], dict(checkpoint) if checkpoint and all(torch.is_tensor(value) for value in checkpoint.values()): return checkpoint, {} raise ValueError("checkpoint contains no valid FPINN model state")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from __future__ import annotations
from collections.abc import Mappingfrom pathlib import Path
import numpy as npimport scipy.ioimport torch
def load_allen_cahn(path: Path) -> dict[str, np.ndarray | tuple[int, int]]: if not path.is_file(): raise FileNotFoundError(f"Allen-Cahn data not found: {path}") data = scipy.io.loadmat(path) missing = {"tt", "x", "uu"}.difference(data) if missing: raise ValueError(f"Allen-Cahn data is missing fields: {sorted(missing)}") time_axis = np.asarray(data["tt"], dtype=np.float64).reshape(-1) space_axis = np.asarray(data["x"], dtype=np.float64).reshape(-1) raw_solution = np.real(np.asarray(data["uu"])) expected_shape = (space_axis.size, time_axis.size) if raw_solution.shape != expected_shape: raise ValueError( f"uu shape must be {expected_shape} in [x,t] order, got {raw_solution.shape}" ) exact_grid = raw_solution.T mesh_x, mesh_t = np.meshgrid(space_axis, time_axis, indexing="xy") coordinates = np.column_stack((mesh_x.ravel(), mesh_t.ravel())) exact = exact_grid.reshape(-1, 1) return { "time": time_axis, "space": space_axis, "coordinates": coordinates, "exact": exact, "grid_shape": exact_grid.shape, }
def sample_training_data( dataset: Mapping, n_train: int, seed: int, device: torch.device, dtype: torch.dtype,) -> tuple[torch.Tensor, torch.Tensor]: coordinates = np.asarray(dataset["coordinates"]) exact = np.asarray(dataset["exact"]) if n_train <= 0 or n_train > coordinates.shape[0]: raise ValueError( f"n_train must be between 1 and {coordinates.shape[0]}, got {n_train}" ) generator = np.random.default_rng(seed) indices = generator.choice(coordinates.shape[0], n_train, replace=False) return ( torch.as_tensor(coordinates[indices], dtype=dtype, device=device), torch.as_tensor(exact[indices], dtype=dtype, device=device), )
def batched_predict( model: torch.nn.Module, coordinates: np.ndarray, batch_size: int, device: torch.device, dtype: torch.dtype,) -> np.ndarray: if batch_size <= 0: raise ValueError("evaluation batch size must be positive") predictions = [] model.eval() with torch.no_grad(): for start in range(0, coordinates.shape[0], batch_size): batch = torch.as_tensor( coordinates[start : start + batch_size], dtype=dtype, device=device ) predictions.append(model.predict_u(batch).cpu().numpy()) return np.concatenate(predictions, axis=0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154from __future__ import annotations
import sysfrom collections.abc import Mappingfrom pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npimport torch
PROJECT_ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(PROJECT_ROOT))sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import ( # noqa: E402 checkpoint_state, load_config, project_path, relative_l2, resolve_device, resolve_dtype,)from data_utils import batched_predict, load_allen_cahn # noqa: E402from model.fpinn import build_model # noqa: E402
DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"TASKS = ("forward", "inverse")
def main() -> None: config_path = DEFAULT_CONFIG.resolve() config = load_config(config_path) common = config["common"] task = str(common["task"]).lower() if task not in TASKS: raise ValueError("common.task must be one of: forward, inverse") task_config = config["tasks"][task] device = resolve_device(str(common["device"])) dtype = resolve_dtype(str(common["dtype"])) weight_dir = project_path(common["weight_dir"], PROJECT_ROOT) result_dir = project_path(common["result_dir"], PROJECT_ROOT) checkpoint_path = weight_dir / task_config["output"]["checkpoint_name"] if not checkpoint_path.is_file(): raise FileNotFoundError( f"checkpoint not found: {checkpoint_path}. Run scripts/train.py first." ) checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True) if not isinstance(checkpoint, Mapping): raise ValueError(f"invalid FPINN checkpoint: {checkpoint_path}") state, metadata = checkpoint_state(checkpoint) checkpoint_task = metadata.get("task", task) if checkpoint_task != task: raise ValueError( f"checkpoint task is {checkpoint_task}, but common.task is {task}" ) model_config = metadata.get("model_config", config["model"]) pde_config = metadata.get("pde_config", task_config["pde"]) data_config = dict(metadata.get("data_config", config["data"])) data_path = project_path(data_config["mat_file"], PROJECT_ROOT) dataset = load_allen_cahn(data_path) model = build_model(task, model_config, pde_config, dtype).to( device=device, dtype=dtype ) model.load_state_dict(state, strict=True) model.eval() prediction = batched_predict( model, np.asarray(dataset["coordinates"]), int(data_config["evaluation_batch_size"]), device, dtype, ) exact = np.asarray(dataset["exact"]) error = relative_l2(prediction, exact) rmse = float(np.sqrt(np.mean((prediction - exact) ** 2))) max_error = float(np.max(np.abs(prediction - exact)))
result_dir.mkdir(parents=True, exist_ok=True) predictions_path = result_dir / task_config["output"]["predictions_name"] figure_path = result_dir / task_config["output"]["figure_name"] payload = { "coordinates": dataset["coordinates"], "exact": exact, "prediction": prediction, "relative_l2": error, "rmse": rmse, "max_abs_error": max_error, } if task == "inverse": payload["lambda_1"] = model.lambda_1.item() payload["lambda_2"] = model.lambda_2.item() np.savez_compressed(predictions_path, **payload)
shape = dataset["grid_shape"] exact_grid = exact.reshape(shape) prediction_grid = prediction.reshape(shape) error_grid = np.abs(prediction_grid - exact_grid) extent = ( float(np.min(dataset["space"])), float(np.max(dataset["space"])), float(np.min(dataset["time"])), float(np.max(dataset["time"])), ) figure, axes = plt.subplots(1, 3, figsize=(15, 4)) for axis, title, field in zip( axes, ("Exact", "FPINN", "Absolute error"), (exact_grid, prediction_grid, error_grid), strict=True, ): image = axis.imshow( field, extent=extent, origin="lower", aspect="auto", cmap="viridis" if title != "Absolute error" else "hot", ) axis.set_title(title) axis.set_xlabel("x") axis.set_ylabel("t") figure.colorbar(image, ax=axis) title = f"Allen-Cahn {task} | L2={error:.3e}" if task == "inverse": title += ( f" | lambda=({model.lambda_1.item():.3e}, " f"{model.lambda_2.item():.3e})" ) figure.suptitle(title) figure.tight_layout() figure.savefig(figure_path, dpi=150) plt.close(figure)
print(f"Config: {config_path}") print(f"Task: {task}") print(f"Data: {data_path}") print(f"Checkpoint: {checkpoint_path}") print(f"Device: {device}") print(f"Relative L2={error:.6e}, RMSE={rmse:.6e}, MaxAbs={max_error:.6e}") if task == "inverse": print( f"Recovered lambda_1={model.lambda_1.item():.8e}, " f"lambda_2={model.lambda_2.item():.8e}" ) print(f"Predictions: {predictions_path}") print(f"Plot: {figure_path}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223from __future__ import annotations
import sysimport timefrom pathlib import Path
import numpy as npimport torch
PROJECT_ROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(PROJECT_ROOT))sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import ( # noqa: E402 load_config, project_path, relative_l2, resolve_device, resolve_dtype, seed_everything,)from data_utils import batched_predict, load_allen_cahn, sample_training_data # noqa: E402from model.fpinn import build_model, loss_components, weighted_loss # noqa: E402
DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"TASKS = ("forward", "inverse")
def main() -> None: config_path = DEFAULT_CONFIG.resolve() config = load_config(config_path) common = config["common"] task = str(common["task"]).lower() if task not in TASKS: raise ValueError("common.task must be one of: forward, inverse") task_config = config["tasks"][task] device = resolve_device(str(common["device"])) dtype = resolve_dtype(str(common["dtype"])) seed = int(common["seed"]) epochs = int(task_config["training"]["epochs"]) lbfgs_iters = int(task_config["training"]["lbfgs_iters"]) learning_rate = float(task_config["training"]["lr"]) if min(epochs, lbfgs_iters) < 0 or epochs + lbfgs_iters == 0: raise ValueError("at least one optimizer iteration count must be positive") if learning_rate <= 0: raise ValueError("learning rate must be positive")
data_config = dict(config["data"]) data_path = project_path(data_config["mat_file"], PROJECT_ROOT) weight_dir = project_path(common["weight_dir"], PROJECT_ROOT) result_dir = project_path(common["result_dir"], PROJECT_ROOT) checkpoint_path = weight_dir / task_config["output"]["checkpoint_name"] history_path = result_dir / task_config["output"]["history_name"] seed_everything(seed)
dataset = load_allen_cahn(data_path) x_train, u_train = sample_training_data( dataset, int(data_config["n_train"]), seed, device, dtype, ) model = build_model(task, config["model"], task_config["pde"], dtype).to( device=device, dtype=dtype ) parameter_count = sum(parameter.numel() for parameter in model.parameters()) if task == "forward": lambda_1 = float(task_config["pde"]["lambda_1"]) lambda_2 = float(task_config["pde"]["lambda_2"]) else: lambda_1 = model.lambda_1 lambda_2 = model.lambda_2
print(f"Config: {config_path}") print(f"Task: {task}") print(f"Data: {data_path}") print(f"Device: {device}") print(f"Training points: {x_train.shape[0]}") print(f"Parameters: {parameter_count:,}")
with torch.enable_grad(): sample = x_train[: min(10, x_train.shape[0])].detach().requires_grad_(True) test_function = sample[:, 0:1].square() + sample[:, 1:2] gradient = torch.autograd.grad( test_function, sample, torch.ones_like(test_function), create_graph=True, )[0] second = torch.autograd.grad( gradient[:, 0:1], sample, torch.ones_like(gradient[:, 0:1]), create_graph=True, )[0][:, 0:1] if not torch.allclose(gradient[:, 1:2], torch.ones_like(second), atol=1.0e-5): raise RuntimeError("u_t autograd validation failed") if not torch.allclose(second, torch.full_like(second, 2.0), atol=1.0e-5): raise RuntimeError("u_xx autograd validation failed") print("Autograd validation: passed")
def current_loss() -> tuple[torch.Tensor, dict[str, torch.Tensor]]: components = loss_components( model, x_train, u_train, x_train, lambda_1, lambda_2 ) return weighted_loss(components, task_config["loss"]), components
def evaluate() -> float: prediction = batched_predict( model, np.asarray(dataset["coordinates"]), int(data_config["evaluation_batch_size"]), device, dtype, ) return relative_l2(prediction, np.asarray(dataset["exact"]))
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) log_interval = int(task_config["training"]["log_interval"]) loss_history = [] l2_history = [] lambda_history = [] best_l2 = evaluate() started = time.time() for epoch in range(1, epochs + 1): loss, components = current_loss() if not torch.isfinite(loss): raise FloatingPointError(f"FPINN loss became non-finite at epoch {epoch}") optimizer.zero_grad(set_to_none=True) loss.backward() optimizer.step() loss_history.append(loss.item()) if task == "inverse": lambda_history.append((model.lambda_1.item(), model.lambda_2.item()))
if epoch == 1 or epoch % log_interval == 0 or epoch == epochs: error = evaluate() l2_history.append((epoch, error)) best_l2 = min(best_l2, error) lambda_text = ( "" if task == "forward" else f" lambda=({model.lambda_1.item():.6e}, {model.lambda_2.item():.6e})" ) print( f"epoch={epoch:6d} loss={loss.item():.3e} " f"data={components['data'].item():.3e} " f"pde={components['pde'].item():.3e} l2={error:.3e}{lambda_text}" )
if lbfgs_iters > 0: lbfgs = torch.optim.LBFGS( model.parameters(), lr=1.0, max_iter=lbfgs_iters, max_eval=max(1, 2 * lbfgs_iters), history_size=50, tolerance_grad=1.0e-5, tolerance_change=float(np.finfo(float).eps), line_search_fn="strong_wolfe", )
def closure() -> torch.Tensor: lbfgs.zero_grad(set_to_none=True) closure_loss, _ = current_loss() if not torch.isfinite(closure_loss): raise FloatingPointError("FPINN L-BFGS loss became non-finite") closure_loss.backward() return closure_loss
lbfgs.step(closure) error = evaluate() l2_history.append((epochs + lbfgs_iters, error)) best_l2 = min(best_l2, error) print(f"L-BFGS relative L2={error:.6e}")
final_l2 = evaluate() elapsed = time.time() - started weight_dir.mkdir(parents=True, exist_ok=True) result_dir.mkdir(parents=True, exist_ok=True) checkpoint = { "task": task, "case": "allen_cahn", "architecture": "fuzzy_pinn", "model_state": model.state_dict(), "model_config": config["model"], "pde_config": task_config["pde"], "data_config": data_config, "seed": seed, "epochs": epochs, "lbfgs_iters": lbfgs_iters, "final_l2": final_l2, } torch.save(checkpoint, checkpoint_path) l2_array = np.asarray(l2_history, dtype=np.float64).reshape(-1, 2) lambda_array = np.asarray(lambda_history, dtype=np.float64).reshape(-1, 2) np.savez_compressed( history_path, loss=np.asarray(loss_history, dtype=np.float64), l2_steps=l2_array[:, 0], l2_values=l2_array[:, 1], lambda_1=lambda_array[:, 0] if lambda_array.size else np.array([]), lambda_2=lambda_array[:, 1] if lambda_array.size else np.array([]), final_l2=final_l2, best_l2=best_l2, elapsed_seconds=elapsed, parameter_count=parameter_count, ) print(f"Final relative L2={final_l2:.6e}, elapsed={elapsed:.1f}s") if task == "inverse": print( f"Recovered lambda_1={model.lambda_1.item():.8e}, " f"lambda_2={model.lambda_2.item():.8e}" ) print(f"Saved checkpoint: {checkpoint_path}") print(f"Saved history: {history_path}")
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:657474331eae29e21f6bfb1bd4ce9bea8d73c39e50e32190a5007826688d311dsize 498456.gitattributes+25-10
README.mdAdded+130
conf/config.yamlAdded+58
configuration.jsonAdded+1
data/AC.matAdded+3
model/__pycache__/fpinn.cpython-311.pycAdded
model/fpinn.pyAdded+190
result/fpinn_forward_history.npzAdded+3
scripts/__pycache__/common.cpython-311.pycAdded
scripts/__pycache__/data_utils.cpython-311.pycAdded
scripts/__pycache__/inference.cpython-311.pycAdded
scripts/__pycache__/train.cpython-311.pycAdded
scripts/common.pyAdded+61
scripts/data_utils.pyAdded+77
scripts/inference.pyAdded+154
scripts/train.pyAdded+223
weight/.gitkeepAdded
weight/fpinn_forward.ptAdded+3