OneScience commited on
Commit
28d9c3b
·
verified ·
1 Parent(s): 3f39354

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -1,35 +1,50 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
  *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
11
  *.model filter=lfs diff=lfs merge=lfs -text
12
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
13
  *.onnx filter=lfs diff=lfs merge=lfs -text
14
  *.ot filter=lfs diff=lfs merge=lfs -text
15
  *.parquet filter=lfs diff=lfs merge=lfs -text
16
  *.pb filter=lfs diff=lfs merge=lfs -text
17
+
 
 
18
  *.pth filter=lfs diff=lfs merge=lfs -text
19
  *.rar filter=lfs diff=lfs merge=lfs -text
 
20
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
22
  *.tflite filter=lfs diff=lfs merge=lfs -text
23
  *.tgz filter=lfs diff=lfs merge=lfs -text
 
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *.tfevents* filter=lfs diff=lfs merge=lfs -text
28
+ *.db* filter=lfs diff=lfs merge=lfs -text
29
+ *.ark* filter=lfs diff=lfs merge=lfs -text
30
+ **/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
31
+ **/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
32
+ **/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
33
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
34
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
35
+ *.gguf* filter=lfs diff=lfs merge=lfs -text
36
+ *.ggml filter=lfs diff=lfs merge=lfs -text
37
+ *.llamafile* filter=lfs diff=lfs merge=lfs -text
38
+ *.pt2 filter=lfs diff=lfs merge=lfs -text
39
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
40
+ *.npy filter=lfs diff=lfs merge=lfs -text
41
+
42
+ *.pickle filter=lfs diff=lfs merge=lfs -text
43
+ *.pkl filter=lfs diff=lfs merge=lfs -text
44
+ *.tar filter=lfs diff=lfs merge=lfs -text
45
+ *.wasm filter=lfs diff=lfs merge=lfs -text
46
  *.zst filter=lfs diff=lfs merge=lfs -text
47
  *tfevents* filter=lfs diff=lfs merge=lfs -text
48
+
49
+ *.npz filter=lfs diff=lfs merge=lfs -text
50
+ *.pt filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ frameworks:
3
+ - pytorch
4
+ language:
5
+ - en
6
+ license: apache-2.0
7
+ tags:
8
+ - OneScience
9
+ - BPINNs
10
+ - Bayesian-physics-informed-neural-networks
11
+ - partial-differential-equations
12
+ - Laplace
13
+ tasks:
14
+ - pde-solving
15
+ ---
16
+ <p align="center">
17
+ <strong>
18
+ <span style="font-size: 30px;">BPINNs</span>
19
+ </strong>
20
+ </p>
21
+
22
+ # Model Overview
23
+
24
+ BPINNs (Bayesian Physics-Informed Neural Networks) incorporate physical-equation constraints into Bayesian neural networks to jointly estimate equation solutions and predictive uncertainty from noisy data. This model package provides an example for solving a one-dimensional Laplace equation:
25
+
26
+ ```text
27
+ u_xx + pi^2 sin(pi x) = 0, x in [0, 1]
28
+ u(x) = sin(pi x)
29
+ ```
30
+
31
+ Paper: B-PINNs: Bayesian physics-informed neural networks for forward and inverse PDE problems with noisy data
32
+ https://doi.org/10.1016/j.jcp.2020.109913
33
+
34
+ # Model Description
35
+
36
+ BPINNs are trained jointly on observational data, boundary conditions, and PDE residuals. By default, the model is optimized with Adam and then refined with L-BFGS. During inference, predictive means and standard deviations can be computed from multiple parameter states stored in a checkpoint. The default training workflow produces only one optimized state; full Bayesian uncertainty quantification requires posterior parameter states obtained through Hamiltonian Monte Carlo (HMC), variational inference, or ensemble sampling.
37
+
38
+ # Use Cases
39
+
40
+ | Use Case | Description |
41
+ | :---: | :--- |
42
+ | One-dimensional Laplace equation | Train the solution jointly from observation points, boundary points, and collocation points |
43
+ | PDE modeling with noisy data | Fit noisy observations subject to physical constraints |
44
+ | Optimizer comparison | Compare the effects of Adam and L-BFGS on PINN convergence |
45
+ | Posterior prediction | Compute predictive means and standard deviations from multiple parameter states |
46
+
47
+ # Usage
48
+
49
+ ## 1. OneCode
50
+
51
+ Use the online OneCode environment for an intelligent, one-click AI for Science (AI4S) programming experience:
52
+
53
+ [Launch OneCode for one-click AI4S programming](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
54
+
55
+ ## 2. Manual Setup
56
+
57
+ **Hardware Requirements**
58
+
59
+ - A GPU or DCU can accelerate full training; a CPU is sufficient for pipeline validation.
60
+ - DCU users must install DTK and a PyTorch environment compatible with the target cluster.
61
+
62
+ ### Download the Model Package
63
+
64
+ ```bash
65
+ modelscope download --model OneScience/BPINNs --local_dir ./BPINNs
66
+ cd BPINNs
67
+ ```
68
+
69
+ ### Set Up the Runtime Environment
70
+
71
+ **DCU Environment**
72
+
73
+ ```bash
74
+ # Activate DTK and Conda first
75
+ conda create -n onescience311 python=3.11 -y
76
+ conda activate onescience311
77
+ pip install onescience[cfd-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
78
+ ```
79
+
80
+ **GPU Environment**
81
+
82
+ ```bash
83
+ # Activate Conda first
84
+ conda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12
85
+ conda activate onescience311
86
+ pip install onescience[cfd-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
87
+ ```
88
+
89
+ ### Training Data
90
+
91
+ This example automatically generates interior observation points, boundary points, PDE collocation points, and a test grid from the analytical solution; no external data files are required. The number of observation and collocation points, noise level, and computational domain can be configured in `conf/config.yaml`.
92
+
93
+ ### Training
94
+
95
+ ```bash
96
+ python scripts/train.py
97
+ ```
98
+
99
+ By default, training produces the base weights at `weight/bpinn_laplace1d.pt` and saves the training history to `result/training_history.npz`.
100
+
101
+ ### Model Weights
102
+
103
+ This repository provides weights trained on the one-dimensional Laplace equation in the `weight/` directory.
104
+
105
+ ### L-BFGS Refinement
106
+
107
+ ```bash
108
+ python scripts/refine.py
109
+ ```
110
+
111
+ By default, refinement produces `weight/bpinn_laplace1d_refined.pt`.
112
+
113
+ ### Inference, Evaluation, and Visualization
114
+
115
+ ```bash
116
+ python scripts/inference.py
117
+ ```
118
+
119
+ Inference loads the refined weights when available and otherwise falls back to the base weights. Predictions and visualizations are saved to `result/`. Model, training, loss, and inference parameters can all be modified in `conf/config.yaml`.
120
+
121
+ # Official OneScience Resources
122
+
123
+ | Platform | OneScience Repository | Skills Repository |
124
+ | --- | --- | --- |
125
+ | Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills |
126
+ | GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
127
+
128
+ # Citations and License
129
+
130
+ - Yang, L., Meng, X., and Karniadakis, G. E. B-PINNs: Bayesian physics-informed neural networks for forward and inverse PDE problems with noisy data. Journal of Computational Physics, 425, 109913, 2021.
131
+ - This model package is released under the Apache-2.0 license and retains attribution to the original paper.
conf/config.yaml ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root:
2
+ common:
3
+ device: "auto"
4
+ dtype: "float64"
5
+ seed: 1234
6
+ weight_dir: "weight"
7
+ result_dir: "result"
8
+
9
+ model:
10
+ name: "BPINN"
11
+ input_dim: 1
12
+ n_layers: 4
13
+ n_neurons: 50
14
+ n_out_sol: 1
15
+ n_out_par: 0
16
+ activation: "tanh"
17
+
18
+ training:
19
+ epochs: 10000
20
+ lr: 0.001
21
+ lbfgs_iters: 2000
22
+ refinement_lr: 1.0
23
+ log_interval: 500
24
+ checkpoint_name: "bpinn_laplace1d.pt"
25
+ refined_checkpoint_name: "bpinn_laplace1d_refined.pt"
26
+
27
+ loss:
28
+ data: 10.0
29
+ pde: 1.0
30
+ boundary: 10.0
31
+
32
+ data:
33
+ domain: [0.0, 1.0]
34
+ n_sol: 200
35
+ n_pde: 1000
36
+ noise_std: 0.0
37
+ test_res: 200
38
+
39
+ inference:
40
+ predictions_name: "bpinn_laplace1d.npz"
41
+ figure_name: "bpinn_laplace1d.png"
42
+ history_name: "training_history.npz"
configuration.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"Pytorch","task":"other"}
data/.gitkeep ADDED
File without changes
model/__pycache__/bpinn.cpython-311.pyc ADDED
Binary file (11.8 kB). View file
 
model/bpinn.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from collections.abc import Mapping, Sequence
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+
10
+ class FCN(nn.Module):
11
+ """Fully connected network used by the BPINN solution model."""
12
+
13
+ def __init__(
14
+ self,
15
+ layer_sizes: Sequence[int],
16
+ activation: str = "tanh",
17
+ dtype: torch.dtype = torch.float64,
18
+ stddev: float | None = None,
19
+ ) -> None:
20
+ super().__init__()
21
+ if len(layer_sizes) < 2:
22
+ raise ValueError("layer_sizes must include input and output widths")
23
+ if activation not in {"tanh", "sin", "sine", "relu", "gelu"}:
24
+ raise ValueError(f"unsupported activation: {activation}")
25
+ if stddev is None:
26
+ stddev = math.sqrt(50.0 / layer_sizes[1])
27
+ if stddev <= 0:
28
+ raise ValueError("stddev must be positive")
29
+
30
+ self.activation = "sin" if activation == "sine" else activation
31
+ self.linears = nn.ModuleList(
32
+ nn.Linear(layer_sizes[index], layer_sizes[index + 1], dtype=dtype)
33
+ for index in range(len(layer_sizes) - 1)
34
+ )
35
+ for linear in self.linears:
36
+ nn.init.trunc_normal_(
37
+ linear.weight,
38
+ mean=0.0,
39
+ std=stddev,
40
+ a=-2.0 * stddev,
41
+ b=2.0 * stddev,
42
+ )
43
+ nn.init.zeros_(linear.bias)
44
+
45
+ def _activate(self, values: torch.Tensor) -> torch.Tensor:
46
+ if self.activation == "gelu":
47
+ return torch.nn.functional.gelu(values)
48
+ return getattr(torch, self.activation)(values)
49
+
50
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
51
+ hidden = inputs
52
+ for linear in self.linears[:-1]:
53
+ hidden = self._activate(linear(hidden))
54
+ return self.linears[-1](hidden)
55
+
56
+
57
+ class PhysNet(nn.Module):
58
+ """Physics-informed network with solution and optional parameter outputs."""
59
+
60
+ def __init__(
61
+ self,
62
+ input_dim: int = 1,
63
+ n_layers: int = 4,
64
+ n_neurons: int = 50,
65
+ n_out_sol: int = 1,
66
+ n_out_par: int = 0,
67
+ activation: str = "tanh",
68
+ dtype: torch.dtype = torch.float64,
69
+ ) -> None:
70
+ super().__init__()
71
+ if min(input_dim, n_layers, n_neurons, n_out_sol) <= 0 or n_out_par < 0:
72
+ raise ValueError("network dimensions must be positive")
73
+ self.n_out_sol = n_out_sol
74
+ self.n_out_par = n_out_par
75
+ output_dim = n_out_sol + n_out_par
76
+ self.fcn = FCN(
77
+ [input_dim, *([n_neurons] * n_layers), output_dim],
78
+ activation=activation,
79
+ dtype=dtype,
80
+ )
81
+
82
+ def forward(self, inputs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
83
+ outputs = self.fcn(inputs)
84
+ solution = outputs[..., : self.n_out_sol]
85
+ parameters = outputs[..., self.n_out_sol :] if self.n_out_par else None
86
+ return solution, parameters
87
+
88
+ def predict_u(self, inputs: torch.Tensor) -> torch.Tensor:
89
+ return self.forward(inputs)[0]
90
+
91
+
92
+ class BPINN(nn.Module):
93
+ """Physics-informed neural network used by the BPINNs workflow."""
94
+
95
+ def __init__(
96
+ self,
97
+ input_dim: int = 1,
98
+ n_layers: int = 4,
99
+ n_neurons: int = 50,
100
+ n_out_sol: int = 1,
101
+ n_out_par: int = 0,
102
+ activation: str = "tanh",
103
+ dtype: torch.dtype = torch.float64,
104
+ ) -> None:
105
+ super().__init__()
106
+ self.net = PhysNet(
107
+ input_dim=input_dim,
108
+ n_layers=n_layers,
109
+ n_neurons=n_neurons,
110
+ n_out_sol=n_out_sol,
111
+ n_out_par=n_out_par,
112
+ activation=activation,
113
+ dtype=dtype,
114
+ )
115
+
116
+ def forward(self, inputs: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
117
+ return self.net(inputs)
118
+
119
+ def predict_u(self, inputs: torch.Tensor) -> torch.Tensor:
120
+ return self.net.predict_u(inputs)
121
+
122
+
123
+ def build_model(config: Mapping, dtype: torch.dtype = torch.float64) -> BPINN:
124
+ return BPINN(
125
+ input_dim=int(config["input_dim"]),
126
+ n_layers=int(config["n_layers"]),
127
+ n_neurons=int(config["n_neurons"]),
128
+ n_out_sol=int(config["n_out_sol"]),
129
+ n_out_par=int(config["n_out_par"]),
130
+ activation=str(config["activation"]),
131
+ dtype=dtype,
132
+ )
133
+
134
+
135
+ def laplace1d_loss_components(
136
+ model: BPINN,
137
+ x_solution: torch.Tensor,
138
+ u_solution: torch.Tensor,
139
+ x_boundary: torch.Tensor,
140
+ u_boundary: torch.Tensor,
141
+ x_pde: torch.Tensor,
142
+ ) -> dict[str, torch.Tensor]:
143
+ solution_prediction = model.predict_u(x_solution)
144
+ boundary_prediction = model.predict_u(x_boundary)
145
+
146
+ pde_points = x_pde.detach().requires_grad_(True)
147
+ pde_prediction = model.predict_u(pde_points)
148
+ first_derivative = torch.autograd.grad(
149
+ pde_prediction,
150
+ pde_points,
151
+ torch.ones_like(pde_prediction),
152
+ create_graph=True,
153
+ )[0]
154
+ second_derivative = torch.autograd.grad(
155
+ first_derivative,
156
+ pde_points,
157
+ torch.ones_like(first_derivative),
158
+ create_graph=True,
159
+ )[0]
160
+ source = torch.pi**2 * torch.sin(torch.pi * pde_points)
161
+ residual = second_derivative + source
162
+ return {
163
+ "data": torch.mean((solution_prediction - u_solution).square()),
164
+ "boundary": torch.mean((boundary_prediction - u_boundary).square()),
165
+ "pde": torch.mean(residual.square()),
166
+ }
167
+
168
+
169
+ def weighted_loss(components: Mapping[str, torch.Tensor], weights: Mapping) -> torch.Tensor:
170
+ return (
171
+ float(weights["data"]) * components["data"]
172
+ + float(weights["boundary"]) * components["boundary"]
173
+ + float(weights["pde"]) * components["pde"]
174
+ )
175
+
176
+
177
+ def posterior_predict(
178
+ model: BPINN,
179
+ states: Sequence[Mapping[str, torch.Tensor]],
180
+ inputs: torch.Tensor,
181
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
182
+ """Compute predictive mean and standard deviation from parameter-state samples."""
183
+ if not states:
184
+ raise ValueError("posterior prediction requires at least one parameter state")
185
+ original_state = {
186
+ key: value.detach().clone() for key, value in model.state_dict().items()
187
+ }
188
+ predictions = []
189
+ try:
190
+ for state in states:
191
+ model.load_state_dict(state, strict=True)
192
+ with torch.no_grad():
193
+ predictions.append(model.predict_u(inputs))
194
+ finally:
195
+ model.load_state_dict(original_state, strict=True)
196
+ samples = torch.stack(predictions)
197
+ return samples.mean(dim=0), samples.std(dim=0, unbiased=False), samples
result/training_history.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f99290cd748a747023763f62c781c21937584e19ca1d9b06078fd3e793fb25a
3
+ size 76767
scripts/__pycache__/common.cpython-311.pyc ADDED
Binary file (8.48 kB). View file
 
scripts/common.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ from collections.abc import Mapping
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ import yaml
10
+
11
+
12
+ def load_config(path: Path) -> dict:
13
+ with path.open("r", encoding="utf-8") as stream:
14
+ config = yaml.safe_load(stream)
15
+ if not isinstance(config, dict) or "root" not in config:
16
+ raise ValueError(f"config must contain a 'root' mapping: {path}")
17
+ return config["root"]
18
+
19
+
20
+ def project_path(value: str | Path, project_root: Path) -> Path:
21
+ path = Path(value).expanduser()
22
+ return path if path.is_absolute() else project_root / path
23
+
24
+
25
+ def resolve_device(requested: str) -> torch.device:
26
+ if requested == "auto":
27
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
28
+ device = torch.device(requested)
29
+ if device.type == "cuda" and not torch.cuda.is_available():
30
+ raise RuntimeError("CUDA/DCU was requested but torch.cuda.is_available() is false")
31
+ return device
32
+
33
+
34
+ def resolve_dtype(name: str) -> torch.dtype:
35
+ try:
36
+ return {"float32": torch.float32, "float64": torch.float64}[name]
37
+ except KeyError as error:
38
+ raise ValueError(f"unsupported dtype: {name}") from error
39
+
40
+
41
+ def seed_everything(seed: int) -> None:
42
+ random.seed(seed)
43
+ np.random.seed(seed)
44
+ torch.manual_seed(seed)
45
+ if torch.cuda.is_available():
46
+ torch.cuda.manual_seed_all(seed)
47
+
48
+
49
+ def exact_solution(values: np.ndarray | torch.Tensor) -> np.ndarray | torch.Tensor:
50
+ if torch.is_tensor(values):
51
+ return torch.sin(torch.pi * values)
52
+ return np.sin(np.pi * values)
53
+
54
+
55
+ def build_laplace_data(
56
+ config: Mapping,
57
+ seed: int,
58
+ device: torch.device,
59
+ dtype: torch.dtype,
60
+ ) -> dict[str, torch.Tensor]:
61
+ domain = config["domain"]
62
+ if len(domain) != 2 or float(domain[0]) >= float(domain[1]):
63
+ raise ValueError("data.domain must contain increasing lower and upper bounds")
64
+ lower, upper = float(domain[0]), float(domain[1])
65
+ n_solution = int(config["n_sol"])
66
+ n_pde = int(config["n_pde"])
67
+ test_resolution = int(config["test_res"])
68
+ if min(n_solution, n_pde, test_resolution) <= 0:
69
+ raise ValueError("n_sol, n_pde, and test_res must be positive")
70
+ noise_std = float(config["noise_std"])
71
+ if noise_std < 0:
72
+ raise ValueError("noise_std must be non-negative")
73
+
74
+ generator = np.random.default_rng(seed)
75
+ x_solution = generator.uniform(lower, upper, (n_solution, 1))
76
+ u_solution = exact_solution(x_solution)
77
+ if noise_std:
78
+ u_solution = u_solution + noise_std * generator.standard_normal(u_solution.shape)
79
+ x_pde = generator.uniform(lower, upper, (n_pde, 1))
80
+ x_boundary = np.array([[lower], [upper]])
81
+ u_boundary = exact_solution(x_boundary)
82
+ x_test = np.linspace(lower, upper, test_resolution)[:, None]
83
+ u_test = exact_solution(x_test)
84
+
85
+ return {
86
+ "x_solution": torch.as_tensor(x_solution, dtype=dtype, device=device),
87
+ "u_solution": torch.as_tensor(u_solution, dtype=dtype, device=device),
88
+ "x_pde": torch.as_tensor(x_pde, dtype=dtype, device=device),
89
+ "x_boundary": torch.as_tensor(x_boundary, dtype=dtype, device=device),
90
+ "u_boundary": torch.as_tensor(u_boundary, dtype=dtype, device=device),
91
+ "x_test": torch.as_tensor(x_test, dtype=dtype, device=device),
92
+ "u_test": torch.as_tensor(u_test, dtype=dtype, device=device),
93
+ }
94
+
95
+
96
+ def relative_l2(prediction: np.ndarray | torch.Tensor, reference: np.ndarray | torch.Tensor) -> float:
97
+ if torch.is_tensor(prediction):
98
+ prediction = prediction.detach().cpu().numpy()
99
+ if torch.is_tensor(reference):
100
+ reference = reference.detach().cpu().numpy()
101
+ prediction_array = np.asarray(prediction).reshape(-1)
102
+ reference_array = np.asarray(reference).reshape(-1)
103
+ return float(
104
+ np.linalg.norm(prediction_array - reference_array)
105
+ / (np.linalg.norm(reference_array) + 1.0e-12)
106
+ )
107
+
108
+
109
+ def checkpoint_state(checkpoint: Mapping) -> tuple[Mapping[str, torch.Tensor], dict]:
110
+ if "model_state" in checkpoint:
111
+ return checkpoint["model_state"], dict(checkpoint)
112
+ if checkpoint and all(torch.is_tensor(value) for value in checkpoint.values()):
113
+ return checkpoint, {}
114
+ raise ValueError("checkpoint contains no valid BPINN model state")
scripts/inference.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from collections.abc import Mapping
5
+ from pathlib import Path
6
+
7
+ import matplotlib
8
+
9
+ matplotlib.use("Agg")
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import torch
13
+
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
16
+ sys.path.insert(0, str(PROJECT_ROOT))
17
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
18
+
19
+ from common import ( # noqa: E402
20
+ build_laplace_data,
21
+ checkpoint_state,
22
+ load_config,
23
+ project_path,
24
+ relative_l2,
25
+ resolve_device,
26
+ resolve_dtype,
27
+ )
28
+ from model.bpinn import build_model, posterior_predict # noqa: E402
29
+
30
+
31
+ DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"
32
+
33
+
34
+ def main() -> None:
35
+ config_path = DEFAULT_CONFIG.resolve()
36
+ config = load_config(config_path)
37
+ common = config["common"]
38
+ device = resolve_device(str(common["device"]))
39
+ dtype = resolve_dtype(str(common["dtype"]))
40
+ weight_dir = project_path(common["weight_dir"], PROJECT_ROOT)
41
+ result_dir = project_path(common["result_dir"], PROJECT_ROOT)
42
+ refined_path = weight_dir / config["training"]["refined_checkpoint_name"]
43
+ base_path = weight_dir / config["training"]["checkpoint_name"]
44
+ checkpoint_path = refined_path if refined_path.is_file() else base_path
45
+ if not checkpoint_path.is_file():
46
+ raise FileNotFoundError(
47
+ f"checkpoint not found: {checkpoint_path}. Run scripts/train.py first."
48
+ )
49
+
50
+ checkpoint = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
51
+ if not isinstance(checkpoint, Mapping):
52
+ raise ValueError(f"invalid BPINN checkpoint: {checkpoint_path}")
53
+ state, metadata = checkpoint_state(checkpoint)
54
+ model_config = metadata.get("model_config", config["model"])
55
+ data_config = dict(metadata.get("data_config", config["data"]))
56
+ seed = int(metadata.get("seed", common["seed"]))
57
+ data = build_laplace_data(data_config, seed, device, dtype)
58
+ model = build_model(model_config, dtype=dtype).to(device=device, dtype=dtype)
59
+ model.load_state_dict(state, strict=True)
60
+ model.eval()
61
+
62
+ posterior_states = metadata.get("posterior_states") or [state]
63
+ mean, standard_deviation, samples = posterior_predict(
64
+ model, posterior_states, data["x_test"]
65
+ )
66
+ mean_numpy = mean.cpu().numpy()
67
+ std_numpy = standard_deviation.cpu().numpy()
68
+ exact_numpy = data["u_test"].cpu().numpy()
69
+ x_numpy = data["x_test"].cpu().numpy()
70
+ error = relative_l2(mean_numpy, exact_numpy)
71
+ rmse = float(np.sqrt(np.mean((mean_numpy - exact_numpy) ** 2)))
72
+ max_error = float(np.max(np.abs(mean_numpy - exact_numpy)))
73
+
74
+ result_dir.mkdir(parents=True, exist_ok=True)
75
+ predictions_path = result_dir / config["inference"]["predictions_name"]
76
+ figure_path = result_dir / config["inference"]["figure_name"]
77
+ np.savez_compressed(
78
+ predictions_path,
79
+ x=x_numpy,
80
+ exact=exact_numpy,
81
+ mean=mean_numpy,
82
+ std=std_numpy,
83
+ samples=samples.cpu().numpy(),
84
+ relative_l2=error,
85
+ rmse=rmse,
86
+ max_abs_error=max_error,
87
+ )
88
+
89
+ x_axis = x_numpy.reshape(-1)
90
+ exact_axis = exact_numpy.reshape(-1)
91
+ mean_axis = mean_numpy.reshape(-1)
92
+ std_axis = std_numpy.reshape(-1)
93
+ absolute_error = np.abs(mean_axis - exact_axis)
94
+ figure, axes = plt.subplots(1, 2, figsize=(12, 4))
95
+ axes[0].plot(x_axis, exact_axis, "k-", linewidth=1.5, label="Exact")
96
+ axes[0].plot(x_axis, mean_axis, "r--", linewidth=1.5, label="BPINN")
97
+ if np.any(std_axis > 0):
98
+ axes[0].fill_between(
99
+ x_axis,
100
+ mean_axis - 2.0 * std_axis,
101
+ mean_axis + 2.0 * std_axis,
102
+ color="red",
103
+ alpha=0.2,
104
+ label="2 std",
105
+ )
106
+ axes[0].set_xlabel("x")
107
+ axes[0].set_ylabel("u")
108
+ axes[0].legend()
109
+ axes[1].semilogy(x_axis, np.maximum(absolute_error, 1.0e-16), "b-")
110
+ axes[1].set_xlabel("x")
111
+ axes[1].set_ylabel("Absolute error")
112
+ figure.tight_layout()
113
+ figure.savefig(figure_path, dpi=150)
114
+ plt.close(figure)
115
+
116
+ print(f"Config: {config_path}")
117
+ print(f"Checkpoint: {checkpoint_path}")
118
+ print(f"Device: {device}")
119
+ print(f"Posterior states: {len(posterior_states)}")
120
+ print(f"Relative L2={error:.6e}, RMSE={rmse:.6e}, MaxAbs={max_error:.6e}")
121
+ print(f"Predictions: {predictions_path}")
122
+ print(f"Plot: {figure_path}")
123
+
124
+
125
+ if __name__ == "__main__":
126
+ main()
scripts/refine.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+
9
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0, str(PROJECT_ROOT))
11
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
12
+
13
+ from common import ( # noqa: E402
14
+ build_laplace_data,
15
+ checkpoint_state,
16
+ load_config,
17
+ project_path,
18
+ relative_l2,
19
+ resolve_device,
20
+ resolve_dtype,
21
+ seed_everything,
22
+ )
23
+ from model.bpinn import ( # noqa: E402
24
+ build_model,
25
+ laplace1d_loss_components,
26
+ weighted_loss,
27
+ )
28
+
29
+
30
+ DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"
31
+
32
+
33
+ def main() -> None:
34
+ config_path = DEFAULT_CONFIG.resolve()
35
+ config = load_config(config_path)
36
+ common = config["common"]
37
+ training = config["training"]
38
+ lbfgs_iters = int(training["lbfgs_iters"])
39
+ refinement_lr = float(training["refinement_lr"])
40
+ if lbfgs_iters <= 0 or refinement_lr <= 0:
41
+ raise ValueError("lbfgs-iters and lr must be positive")
42
+ device = resolve_device(str(common["device"]))
43
+ dtype = resolve_dtype(str(common["dtype"]))
44
+ weight_dir = project_path(common["weight_dir"], PROJECT_ROOT)
45
+ input_path = weight_dir / training["checkpoint_name"]
46
+ output_path = weight_dir / training["refined_checkpoint_name"]
47
+ if not input_path.is_file():
48
+ raise FileNotFoundError(f"checkpoint not found: {input_path}")
49
+ checkpoint = torch.load(input_path, map_location="cpu", weights_only=True)
50
+ state, metadata = checkpoint_state(checkpoint)
51
+ model_config = metadata.get("model_config", config["model"])
52
+ data_config = metadata.get("data_config", config["data"])
53
+ loss_weights = metadata.get("loss_weights", config["loss"])
54
+ seed = int(metadata.get("seed", common["seed"]))
55
+ seed_everything(seed)
56
+ data = build_laplace_data(data_config, seed, device, dtype)
57
+ model = build_model(model_config, dtype=dtype).to(device=device, dtype=dtype)
58
+ model.load_state_dict(state, strict=True)
59
+
60
+ def loss_value() -> torch.Tensor:
61
+ components = laplace1d_loss_components(
62
+ model,
63
+ data["x_solution"],
64
+ data["u_solution"],
65
+ data["x_boundary"],
66
+ data["u_boundary"],
67
+ data["x_pde"],
68
+ )
69
+ return weighted_loss(components, loss_weights)
70
+
71
+ lbfgs = torch.optim.LBFGS(
72
+ model.parameters(),
73
+ lr=refinement_lr,
74
+ max_iter=lbfgs_iters,
75
+ max_eval=max(1, 2 * lbfgs_iters),
76
+ history_size=50,
77
+ line_search_fn="strong_wolfe",
78
+ )
79
+
80
+ def closure() -> torch.Tensor:
81
+ lbfgs.zero_grad(set_to_none=True)
82
+ loss = loss_value()
83
+ if not torch.isfinite(loss):
84
+ raise FloatingPointError("BPINN refinement loss became non-finite")
85
+ loss.backward()
86
+ return loss
87
+
88
+ print(f"Input checkpoint: {input_path}")
89
+ print(f"Device: {device}")
90
+ lbfgs.step(closure)
91
+ with torch.no_grad():
92
+ prediction = model.predict_u(data["x_test"])
93
+ error = relative_l2(prediction, data["u_test"])
94
+ refined = dict(metadata)
95
+ refined.update(
96
+ {
97
+ "case": "laplace1d",
98
+ "architecture": "bpinn",
99
+ "model_state": model.state_dict(),
100
+ "model_config": model_config,
101
+ "data_config": data_config,
102
+ "loss_weights": loss_weights,
103
+ "seed": seed,
104
+ "refinement_iters": lbfgs_iters,
105
+ "final_l2": error,
106
+ }
107
+ )
108
+ output_path.parent.mkdir(parents=True, exist_ok=True)
109
+ torch.save(refined, output_path)
110
+ print(f"Relative L2 after refinement={error:.6e}")
111
+ print(f"Saved checkpoint: {output_path}")
112
+
113
+
114
+ if __name__ == "__main__":
115
+ main()
scripts/train.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import time
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+
10
+
11
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
12
+ sys.path.insert(0, str(PROJECT_ROOT))
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+
15
+ from common import ( # noqa: E402
16
+ build_laplace_data,
17
+ load_config,
18
+ project_path,
19
+ relative_l2,
20
+ resolve_device,
21
+ resolve_dtype,
22
+ seed_everything,
23
+ )
24
+ from model.bpinn import ( # noqa: E402
25
+ build_model,
26
+ laplace1d_loss_components,
27
+ weighted_loss,
28
+ )
29
+
30
+
31
+ DEFAULT_CONFIG = PROJECT_ROOT / "conf" / "config.yaml"
32
+
33
+
34
+ def main() -> None:
35
+ config_path = DEFAULT_CONFIG.resolve()
36
+ config = load_config(config_path)
37
+ common = config["common"]
38
+ device = resolve_device(str(common["device"]))
39
+ dtype = resolve_dtype(str(common["dtype"]))
40
+ seed = int(common["seed"])
41
+ epochs = int(config["training"]["epochs"])
42
+ lbfgs_iters = int(config["training"]["lbfgs_iters"])
43
+ learning_rate = float(config["training"]["lr"])
44
+ if min(epochs, lbfgs_iters) < 0 or epochs + lbfgs_iters == 0:
45
+ raise ValueError("at least one non-negative optimizer iteration count must be positive")
46
+ if learning_rate <= 0:
47
+ raise ValueError("learning rate must be positive")
48
+
49
+ data_config = dict(config["data"])
50
+ weight_dir = project_path(common["weight_dir"], PROJECT_ROOT)
51
+ result_dir = project_path(common["result_dir"], PROJECT_ROOT)
52
+ checkpoint_path = weight_dir / config["training"]["checkpoint_name"]
53
+ history_path = result_dir / config["inference"]["history_name"]
54
+ seed_everything(seed)
55
+
56
+ print(f"Config: {config_path}")
57
+ print(f"Device: {device}")
58
+ print(f"Data config: {data_config}")
59
+ data = build_laplace_data(data_config, seed, device, dtype)
60
+
61
+ with torch.enable_grad():
62
+ test_points = data["x_test"].detach().requires_grad_(True)
63
+ exact = torch.sin(torch.pi * test_points)
64
+ first = torch.autograd.grad(
65
+ exact, test_points, torch.ones_like(exact), create_graph=True
66
+ )[0]
67
+ second = torch.autograd.grad(
68
+ first, test_points, torch.ones_like(first), create_graph=True
69
+ )[0]
70
+ max_residual = torch.max(
71
+ torch.abs(second + torch.pi**2 * torch.sin(torch.pi * test_points))
72
+ ).item()
73
+ if max_residual > 1.0e-8:
74
+ raise RuntimeError(f"Laplace autograd validation failed: {max_residual:.3e}")
75
+ print(f"PDE autograd validation: {max_residual:.3e}")
76
+
77
+ model = build_model(config["model"], dtype=dtype).to(device=device, dtype=dtype)
78
+ parameter_count = sum(parameter.numel() for parameter in model.parameters())
79
+ print(f"Parameters: {parameter_count:,}")
80
+
81
+ def loss_value() -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
82
+ components = laplace1d_loss_components(
83
+ model,
84
+ data["x_solution"],
85
+ data["u_solution"],
86
+ data["x_boundary"],
87
+ data["u_boundary"],
88
+ data["x_pde"],
89
+ )
90
+ return weighted_loss(components, config["loss"]), components
91
+
92
+ def evaluate() -> float:
93
+ with torch.no_grad():
94
+ prediction = model.predict_u(data["x_test"])
95
+ return relative_l2(prediction, data["u_test"])
96
+
97
+ optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
98
+ loss_history = []
99
+ l2_history = []
100
+ log_interval = int(config["training"]["log_interval"])
101
+ best_l2 = evaluate()
102
+ started = time.time()
103
+ print(
104
+ f"Adam epochs={epochs} lr={learning_rate:g}, "
105
+ f"L-BFGS iterations={lbfgs_iters}"
106
+ )
107
+ for epoch in range(1, epochs + 1):
108
+ loss, components = loss_value()
109
+ if not torch.isfinite(loss):
110
+ raise FloatingPointError(f"BPINN loss became non-finite at epoch {epoch}")
111
+ optimizer.zero_grad(set_to_none=True)
112
+ loss.backward()
113
+ optimizer.step()
114
+ loss_history.append(loss.item())
115
+
116
+ if epoch == 1 or epoch % log_interval == 0 or epoch == epochs:
117
+ error = evaluate()
118
+ l2_history.append((epoch, error))
119
+ best_l2 = min(best_l2, error)
120
+ print(
121
+ f"epoch={epoch:6d} loss={loss.item():.3e} "
122
+ f"data={components['data'].item():.3e} "
123
+ f"boundary={components['boundary'].item():.3e} "
124
+ f"pde={components['pde'].item():.3e} l2={error:.3e}"
125
+ )
126
+
127
+ if lbfgs_iters > 0:
128
+ lbfgs = torch.optim.LBFGS(
129
+ model.parameters(),
130
+ lr=1.0,
131
+ max_iter=lbfgs_iters,
132
+ max_eval=max(1, 2 * lbfgs_iters),
133
+ history_size=50,
134
+ line_search_fn="strong_wolfe",
135
+ )
136
+
137
+ def closure() -> torch.Tensor:
138
+ lbfgs.zero_grad(set_to_none=True)
139
+ closure_loss, _ = loss_value()
140
+ if not torch.isfinite(closure_loss):
141
+ raise FloatingPointError("BPINN L-BFGS loss became non-finite")
142
+ closure_loss.backward()
143
+ return closure_loss
144
+
145
+ lbfgs.step(closure)
146
+ error = evaluate()
147
+ l2_history.append((epochs + lbfgs_iters, error))
148
+ best_l2 = min(best_l2, error)
149
+ print(f"L-BFGS relative L2={error:.6e}")
150
+
151
+ final_l2 = evaluate()
152
+ elapsed = time.time() - started
153
+ weight_dir.mkdir(parents=True, exist_ok=True)
154
+ result_dir.mkdir(parents=True, exist_ok=True)
155
+ checkpoint = {
156
+ "case": "laplace1d",
157
+ "architecture": "bpinn",
158
+ "model_state": model.state_dict(),
159
+ "model_config": config["model"],
160
+ "data_config": data_config,
161
+ "loss_weights": config["loss"],
162
+ "seed": seed,
163
+ "epochs": epochs,
164
+ "lbfgs_iters": lbfgs_iters,
165
+ "final_l2": final_l2,
166
+ }
167
+ torch.save(checkpoint, checkpoint_path)
168
+ l2_array = np.asarray(l2_history, dtype=np.float64).reshape(-1, 2)
169
+ np.savez_compressed(
170
+ history_path,
171
+ loss=np.asarray(loss_history, dtype=np.float64),
172
+ l2_steps=l2_array[:, 0],
173
+ l2_values=l2_array[:, 1],
174
+ final_l2=final_l2,
175
+ best_l2=best_l2,
176
+ elapsed_seconds=elapsed,
177
+ parameter_count=parameter_count,
178
+ )
179
+ print(f"Final relative L2={final_l2:.6e}, elapsed={elapsed:.1f}s")
180
+ print(f"Saved checkpoint: {checkpoint_path}")
181
+ print(f"Saved history: {history_path}")
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
weight/.gitkeep ADDED
File without changes
weight/bpinn_laplace1d.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9327aefc675b574aa262ec495528398a6b696b972810cfabb4152ebb8200b660
3
+ size 66920