OneScience commited on
Commit
7087ec2
·
verified ·
1 Parent(s): d97aae1

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ tags:
6
+ - OneScience
7
+ - BENO
8
+ - elliptic PDEs
9
+ - boundary-embedded neural operator
10
+ frameworks: PyTorch
11
+ ---
12
+
13
+ <p align="center">
14
+ <strong>
15
+ <span style="font-size: 30px;">BENO</span>
16
+ </strong>
17
+ </p>
18
+
19
+ # Model Overview
20
+
21
+ BENO is a boundary-embedded neural operator developed by researchers at Peking University for solving elliptic PDEs subject to complex boundary conditions. It enables rapid prediction of steady-state physical fields across varying geometries and nonhomogeneous boundary conditions.
22
+
23
+ Paper: [BENO: Boundary-embedded Neural Operators for Elliptic PDEs](https://openreview.net/forum?id=ZZTkLDRmkg)
24
+
25
+ # Model Description
26
+ BENO employs a boundary-embedded neural operator architecture that combines a dual-branch graph neural network with a Transformer. Trained on the BENO dataset, it predicts steady-state physical fields governed by elliptic PDEs such as the Poisson and Laplace equations on complex geometries with nonhomogeneous boundary conditions.
27
+
28
+ # Use Cases
29
+
30
+ | Use Case | Description |
31
+ | ---------- | --------------------------------- |
32
+ | Elliptic PDE solving | Rapidly approximate steady-state boundary-value problems such as the Poisson and Laplace equations |
33
+ | Complex boundary modeling | Capture the effects of free-form boundaries, irregular domains, and nonhomogeneous boundary values on the solution field |
34
+ | Steady-state field prediction | Predict equilibrium physical fields determined jointly by source terms and boundary conditions |
35
+ | Numerical solver acceleration | Replace or augment conventional FEM, FDM, and FVM workflows to improve inference efficiency |
36
+
37
+ # Usage
38
+ ## 1. OneCode
39
+
40
+ Use the online OneCode environment for an intelligent, one-click AI for Science (AI4S) programming experience:
41
+
42
+ [Launch OneCode for one-click AI4S programming](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
43
+
44
+ ## 2. Manual Setup
45
+
46
+ **Hardware Requirements**
47
+
48
+ - A GPU or DCU is recommended.
49
+ - A CPU can be used for import checks and small-scale pipeline validation, but full training and inference will be slow.
50
+ - DCU users must install DTK in advance. DTK 25.04.2 or later, or the OneScience-recommended version for the target cluster, is recommended.
51
+
52
+ ### Download the Model Package
53
+
54
+ ```bash
55
+ modelscope download --model OneScience/BENO --local_dir ./BENO
56
+ cd BENO
57
+ ```
58
+
59
+ ### Set Up the Runtime Environment
60
+
61
+
62
+ **DCU Environment**
63
+
64
+ ```bash
65
+ # Activate DTK and Conda first
66
+ conda create -n onescience311 python=3.11 -y
67
+ conda activate onescience311
68
+ # Installation with uv is also supported
69
+ pip install onescience[cfd-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
70
+ ```
71
+
72
+ **GPU Environment**
73
+ ```bash
74
+ # Activate Conda first
75
+ conda create -n onescience311 python=3.11 -y libstdcxx-ng=12 libgcc-ng=12 gcc_linux-64=12 gxx_linux-64=12
76
+ conda activate onescience311
77
+ # Installation with uv is also supported
78
+ pip install onescience[cfd-gpu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
79
+ ```
80
+
81
+ ### Training Data
82
+ The OneScience community provides the `beno` dataset for training. Download it with the command below and verify that the data path in `config/config.yaml` is configured correctly:
83
+
84
+ ```bash
85
+ modelscope download --dataset OneScience/beno --local_dir ./data
86
+ ```
87
+ The complete dataset is also available from the [official download link](https://drive.google.com/file/d/11PbUrzJ-b18VhFGY_uICSciCkeGrsaTZ/view).
88
+
89
+ ### Training
90
+
91
+ Single GPU:
92
+
93
+ ```bash
94
+ python scripts/train.py
95
+ ```
96
+
97
+ Multiple GPUs:
98
+ ```
99
+ torchrun --standalone --nnodes=<num_nodes> --nproc_per_node=<num_GPUs> scripts/train.py
100
+ ```
101
+
102
+ ### Model Weights
103
+ This repository will provide weights trained on the BENO dataset in the `weights/` directory. The weights will be uploaded soon.
104
+
105
+ ### Inference
106
+
107
+ ```bash
108
+ python scripts/inference.py
109
+ ```
110
+
111
+ ### Evaluation and Visualization
112
+
113
+ ```bash
114
+ python scripts/result.py
115
+ ```
116
+
117
+ # Official OneScience Resources
118
+
119
+ | Platform | OneScience Repository | Skills Repository |
120
+ | --- | --- | --- |
121
+ | Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills |
122
+ | GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
123
+
124
+ # Citations and License
125
+
126
+ - Original BENO paper: [BENO: Boundary-embedded Neural Operators for Elliptic PDEs](https://proceedings.iclr.cc/paper_files/paper/2024/file/218ca0d92e6ed8f9db00621e103dc70c-Paper-Conference.pdf)
127
+ - This repository retains source attribution and has been adapted for automated execution through OneScience and ModelScope. Before public redistribution, verify the applicable licensing requirements of the upstream project.
conf/config.yaml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root:
2
+ datapipe:
3
+ source:
4
+ data_dir: "${ONESCIENCE_BENO_DATA_DIR}/Dirichlet/"
5
+ cache_dir: "./cache_data"
6
+ file_prefix: "N8_smoke"
7
+ verbose: false
8
+
9
+ data:
10
+ name: "BENO_Elliptic"
11
+ ntrain: 2
12
+ ntest: 1
13
+ resolution: 8
14
+ ns: 4
15
+ domain_bounds: [[0, 1], [0, 1]]
16
+
17
+ dataloader:
18
+ batch_size: 1
19
+ num_workers: 0
20
+ pin_memory: false
21
+
22
+ model:
23
+ name: "HeteroGNS"
24
+ nnode_in_features: 10
25
+ nnode_out_features: 1
26
+ nedge_in_features: 7
27
+ nmlp_layers: 2
28
+ act: "relu"
29
+ boundary_dim: 16
30
+ trans_layer: 1
31
+ latent_dim: 16
32
+ nmessage_passing_steps: 1
33
+ mlp_hidden_dim: 16
34
+
35
+ training:
36
+ device: "cpu"
37
+ output_dir: "./weight"
38
+ epochs: 1
39
+ save_period: 1
40
+ checkpoint_name: "model_epoch_{epoch}.pt"
41
+ seed: 2025
42
+
43
+ optimizer:
44
+ name: "Adam"
45
+ lr: 1.0e-3
46
+ weight_decay: 5.0e-4
47
+
48
+ scheduler:
49
+ name: "CosineAnnealingWarmRestarts"
50
+ T_0: 2
51
+ T_mult: 1
52
+
53
+ inference:
54
+ device: "cpu"
55
+ checkpoint_dir: "./weight"
56
+ checkpoint_path: ""
57
+ result_dir: "./result/output"
58
+ picture_dir: "./result/picture"
59
+ metrics_path: "./result/metrics.json"
60
+ num_visualize: 1
61
+
62
+ fake_data:
63
+ root_dir: "./data"
64
+ seed: 2025
65
+ boundary_points: 128
66
+ noise_std: 0.001
configuration.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "framework": "Pytorch",
3
+ "task": "other",
4
+ "model": {
5
+ "type": "BENO",
6
+ "entrypoint": "model.HeteroGNS"
7
+ },
8
+ "pipeline": {
9
+ "fake_data": "scripts/fake_data.py",
10
+ "train": "scripts/train.py",
11
+ "inference": "scripts/inference.py",
12
+ "result": "scripts/result.py"
13
+ }
14
+ }
model/BE_MPNN.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch_geometric.nn import MessagePassing
5
+ from .transformer import *
6
+
7
+ def build_mlp(
8
+ input_size: int,
9
+ hidden_layer_sizes: List[int],
10
+ output_size: int = None,
11
+ output_activation: nn.Module = nn.Identity,
12
+ activation: nn.Module = nn.ReLU) -> nn.Module:
13
+
14
+ # Size of each layer
15
+ layer_sizes = [input_size] + hidden_layer_sizes
16
+ if output_size:
17
+ layer_sizes.append(output_size)
18
+
19
+ # Number of layers
20
+ nlayers = len(layer_sizes) - 1
21
+
22
+ # Create a list of activation functions and
23
+ # set the last element to output activation function
24
+ act = [activation for i in range(nlayers)]
25
+ act[-1] = output_activation
26
+
27
+ # Create a torch sequential container
28
+ mlp = nn.Sequential()
29
+ for i in range(nlayers):
30
+ mlp.add_module("NN-" + str(i), nn.Linear(layer_sizes[i],
31
+ layer_sizes[i + 1]))
32
+ mlp.add_module("Act-" + str(i), act[i]())
33
+
34
+ return mlp
35
+
36
+
37
+ class Encoder(nn.Module):
38
+
39
+
40
+ def __init__(
41
+ self,
42
+ nnode_in_features: int,
43
+ nnode_out_features: int, #latent dim=128
44
+ nedge_in_features: int,
45
+ nedge_out_features: int,
46
+ nmlp_layers: int,
47
+ mlp_hidden_dim: int,
48
+ activation:nn.Module,):
49
+
50
+ super(Encoder, self).__init__()
51
+ # Encode node features as an MLP
52
+ self.node_fn = nn.Sequential(*[build_mlp(nnode_in_features,
53
+ [mlp_hidden_dim
54
+ for _ in range(nmlp_layers)],
55
+ nnode_out_features,activation=activation),
56
+ nn.LayerNorm(nnode_out_features)])
57
+ # Encode edge features as an MLP
58
+ self.edge_fn = nn.Sequential(*[build_mlp(nedge_in_features,
59
+ [mlp_hidden_dim
60
+ for _ in range(nmlp_layers)],
61
+ nedge_out_features,activation=activation),
62
+ nn.LayerNorm(nedge_out_features)])
63
+
64
+ self.node_fn_inbd = nn.Sequential(*[build_mlp(nnode_in_features,
65
+ [mlp_hidden_dim
66
+ for _ in range(nmlp_layers)],
67
+ nnode_out_features,activation=activation),
68
+ nn.LayerNorm(nnode_out_features)])
69
+
70
+ self.edge_fn_inbd = nn.Sequential(*[build_mlp(nedge_in_features,
71
+ [mlp_hidden_dim
72
+ for _ in range(nmlp_layers)],
73
+ nedge_out_features,activation=activation),
74
+ nn.LayerNorm(nedge_out_features)])
75
+
76
+ def forward(
77
+ self,
78
+ x: torch.tensor,
79
+ edge_features: torch.tensor,
80
+ x_inbd:torch.tensor,
81
+ edge_inbd_features: torch.tensor):
82
+
83
+ return self.node_fn(x), self.edge_fn(edge_features), self.node_fn_inbd(x_inbd), self.edge_fn_inbd(edge_inbd_features)
84
+
85
+
86
+ class InteractionNetwork(MessagePassing):
87
+ def __init__(
88
+ self,
89
+ nnode_in: int,
90
+ nnode_out: int,
91
+ nedge_in: int,
92
+ nedge_out: int,
93
+ nmlp_layers: int,
94
+ mlp_hidden_dim: int,
95
+ boundary_dim: int,
96
+ trans_layer:int,
97
+ activation: nn.Module = nn.ReLU
98
+ ):
99
+
100
+ # Aggregate features from neighbors
101
+ super(InteractionNetwork, self).__init__(aggr='mean')
102
+ # Node MLP
103
+ self.node_fn = nn.Sequential(*[build_mlp(nnode_in + nedge_out + boundary_dim,
104
+ [mlp_hidden_dim
105
+ for _ in range(nmlp_layers)],
106
+ nnode_out,activation=activation),
107
+ nn.LayerNorm(nnode_out)])
108
+
109
+ self.edge_fn = nn.Sequential(*[build_mlp(nnode_in + nnode_in + nedge_in,
110
+ [mlp_hidden_dim
111
+ for _ in range(nmlp_layers)],
112
+ nedge_out,activation=activation),
113
+ nn.LayerNorm(nedge_out)])
114
+
115
+ #boundary
116
+ self.boundary_fn = Transformer(enc_in = 3, d_model = boundary_dim, n_heads = 2, enc_layers = trans_layer)
117
+
118
+ def forward(self,
119
+ x: torch.tensor,
120
+ edge_index: torch.tensor,
121
+ edge_features: torch.tensor,
122
+ boundary: torch.tensor,
123
+
124
+ ):
125
+
126
+ boundary = boundary.unsqueeze(0).float()
127
+
128
+ boundary = self.boundary_fn(boundary)
129
+
130
+ x_residual = x.clone()
131
+ edge_features_residual = edge_features.clone()
132
+
133
+ x, edge_features = self.propagate(
134
+ edge_index=edge_index, x=x, edge_features=edge_features, boundary=boundary)
135
+
136
+
137
+ return x + x_residual, edge_features + edge_features_residual
138
+
139
+ def message(self,
140
+ x_i: torch.tensor,
141
+ x_j: torch.tensor,
142
+ edge_features: torch.tensor,
143
+ boundary: torch.tensor
144
+ ) -> torch.tensor:
145
+
146
+ # Concat edge features with a final shape of [nedges, latent_dim*3]
147
+
148
+ edge_features = torch.cat([x_i, x_j, edge_features], dim=-1)
149
+
150
+ edge_features = self.edge_fn(edge_features)
151
+ return edge_features
152
+
153
+ def update(self,
154
+ x_updated: torch.tensor,
155
+ x: torch.tensor,
156
+ edge_features: torch.tensor,
157
+ boundary: torch.tensor
158
+ ):
159
+
160
+ # Concat node features with a final shape of
161
+ boundary_all = boundary.repeat(x.shape[0], 1)
162
+ x_updated = torch.cat([x_updated, x,boundary_all], dim=-1)
163
+ x_updated = self.node_fn(x_updated)
164
+
165
+ return x_updated, edge_features
166
+
167
+ class Processor(MessagePassing):
168
+
169
+
170
+ def __init__(
171
+ self,
172
+ nnode_in: int,
173
+ nnode_out: int,
174
+ nedge_in: int,
175
+ nedge_out: int,
176
+ nmessage_passing_steps: int,
177
+ nmlp_layers: int,
178
+ mlp_hidden_dim: int,
179
+ boundary_dim: int,
180
+ trans_layer:int,
181
+ activation:nn.Module
182
+ ):
183
+
184
+ super(Processor, self).__init__(aggr='mean')
185
+ # Create a stack of M Graph Networks GNs.
186
+ self.gnn_stacks = nn.ModuleList([
187
+ InteractionNetwork(
188
+ nnode_in=nnode_in,
189
+ nnode_out=nnode_out,
190
+ nedge_in=nedge_in,
191
+ nedge_out=nedge_out,
192
+ nmlp_layers=nmlp_layers,
193
+ mlp_hidden_dim=mlp_hidden_dim,
194
+ boundary_dim=boundary_dim,
195
+ trans_layer=trans_layer,
196
+ activation=activation
197
+ ) for _ in range(nmessage_passing_steps)])
198
+
199
+ self.gnn_stacks_inbd = nn.ModuleList([
200
+ InteractionNetwork(
201
+ nnode_in=nnode_in,
202
+ nnode_out=nnode_out,
203
+ nedge_in=nedge_in,
204
+ nedge_out=nedge_out,
205
+ nmlp_layers=nmlp_layers,
206
+ mlp_hidden_dim=mlp_hidden_dim,
207
+ boundary_dim=boundary_dim,
208
+ trans_layer=trans_layer,
209
+ activation=activation,
210
+ ) for _ in range(nmessage_passing_steps)])
211
+
212
+
213
+ def forward(self,
214
+ x: torch.tensor,
215
+ edge_index: torch.tensor,
216
+ edge_features: torch.tensor,
217
+ boundary:torch.tensor,
218
+ x_inbd: torch.tensor,
219
+ edge_inbd_index: torch.tensor,
220
+ edge_inbd_features: torch.tensor,
221
+ boundary_inbd:torch.tensor):
222
+
223
+ for gnn in self.gnn_stacks:
224
+ x, edge_features= gnn(x, edge_index, edge_features,boundary )
225
+
226
+ for gnn in self.gnn_stacks_inbd:
227
+ x_inbd, edge_inbd_features = gnn(x_inbd, edge_inbd_index, edge_inbd_features,boundary_inbd)
228
+
229
+ return x, edge_features, x_inbd, edge_inbd_features
230
+
231
+ class Decoder(nn.Module):
232
+
233
+
234
+ def __init__(
235
+ self,
236
+ nnode_in: int,
237
+ nnode_out: int,
238
+ nmlp_layers: int,
239
+ mlp_hidden_dim: int,
240
+ activation:nn.Module):
241
+
242
+ super(Decoder, self).__init__()
243
+ self.node_fn = build_mlp(
244
+ nnode_in, [mlp_hidden_dim for _ in range(nmlp_layers)], nnode_out,activation=activation)
245
+ self.node_fn_inbd = build_mlp(
246
+ nnode_in, [mlp_hidden_dim for _ in range(nmlp_layers)], nnode_out,activation=activation)
247
+
248
+ def forward(self,
249
+ x: torch.tensor,
250
+ x_inbd: torch.tensor):
251
+ u1=self.node_fn(x)
252
+ u2=self.node_fn_inbd(x_inbd)
253
+ u=u1+u2
254
+
255
+ return u
256
+
257
+ class HeteroGNS(nn.Module):
258
+ def __init__(
259
+ self,
260
+ nnode_in_features: int,
261
+ nnode_out_features: int,
262
+ nedge_in_features: int,
263
+ latent_dim: int = 128,
264
+ nmessage_passing_steps: int = 10,
265
+ nmlp_layers: int = 2,
266
+ mlp_hidden_dim: int = 128,
267
+ activation: nn.Module = nn.ELU,
268
+ boundary_dim: int=128,
269
+ trans_layer: int =3,
270
+ ):
271
+
272
+ super(HeteroGNS, self).__init__()
273
+ self._encoder = Encoder(
274
+ nnode_in_features=nnode_in_features,
275
+ nnode_out_features=latent_dim,
276
+ nedge_in_features=nedge_in_features,
277
+ nedge_out_features=latent_dim,
278
+ nmlp_layers=nmlp_layers,
279
+ mlp_hidden_dim=mlp_hidden_dim,
280
+ activation=activation,
281
+
282
+
283
+ )
284
+ self._processor = Processor(
285
+ nnode_in=latent_dim,
286
+ nnode_out=latent_dim,
287
+ nedge_in=latent_dim,
288
+ nedge_out=latent_dim,
289
+ nmessage_passing_steps=nmessage_passing_steps,
290
+ nmlp_layers=nmlp_layers,
291
+ mlp_hidden_dim=mlp_hidden_dim,
292
+ boundary_dim = boundary_dim,
293
+ trans_layer = trans_layer,
294
+ activation=activation,
295
+ )
296
+ self._decoder = Decoder(
297
+ nnode_in=latent_dim,
298
+ nnode_out=nnode_out_features,
299
+ nmlp_layers=nmlp_layers,
300
+ mlp_hidden_dim=mlp_hidden_dim,
301
+ activation=activation,
302
+
303
+ )
304
+
305
+ def forward(self,data):
306
+
307
+ x, edge_index, edge_features,boundary = data['G1'].x, data['G1'].edge_index, data['G1'].edge_features,data['G1'].boundary
308
+ x_inbd, edge_inbd_index, edge_inbd_features,boundary_inbd = data['G2'].x, data['G2'].edge_index,data['G2'].edge_features,data['G2'].boundary
309
+
310
+ x, edge_features,x_inbd,edge_inbd_features = self._encoder(x, edge_features,x_inbd,edge_inbd_features)
311
+
312
+ x, edge_features, x_inbd, edge_inbd_features = self._processor(x, edge_index, edge_features, boundary,x_inbd,edge_inbd_index, edge_inbd_features,boundary_inbd)
313
+
314
+ u = self._decoder(x,x_inbd)
315
+
316
+ return u
model/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .BE_MPNN import HeteroGNS
2
+
3
+ __all__ = ["HeteroGNS"]
model/__pycache__/BE_MPNN.cpython-311.pyc ADDED
Binary file (15.6 kB). View file
 
model/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (271 Bytes). View file
 
model/__pycache__/transformer.cpython-311.pyc ADDED
Binary file (37.8 kB). View file
 
model/transformer.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import numpy as np
5
+ import math
6
+ from math import sqrt
7
+
8
+
9
+ class PositionalEmbedding(nn.Module):
10
+ def __init__(self, d_model, max_len=5000):
11
+ super(PositionalEmbedding, self).__init__()
12
+ # Compute the positional encodings once in log space.
13
+ pe = torch.zeros(max_len, d_model).float()
14
+ pe.require_grad = False
15
+
16
+ position = torch.arange(0, max_len).float().unsqueeze(1)
17
+ div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()
18
+
19
+ pe[:, 0::2] = torch.sin(position * div_term)
20
+ pe[:, 1::2] = torch.cos(position * div_term)
21
+
22
+ pe = pe.unsqueeze(0)
23
+ self.register_buffer('pe', pe)
24
+
25
+ def forward(self, x):
26
+ return self.pe[:, :x.size(1)]
27
+
28
+
29
+ class TokenEmbedding(nn.Module):
30
+ def __init__(self, c_in, d_model):
31
+ super(TokenEmbedding, self).__init__()
32
+ padding = 1 if torch.__version__ >= '1.5.0' else 2
33
+ self.tokenConv = nn.Conv1d(in_channels=c_in, out_channels=d_model,
34
+ kernel_size=3, padding=padding, padding_mode='circular', bias=False)
35
+ for m in self.modules():
36
+ if isinstance(m, nn.Conv1d):
37
+ nn.init.kaiming_normal_(m.weight, mode='fan_in', nonlinearity='leaky_relu')
38
+
39
+ def forward(self, x):
40
+ x = self.tokenConv(x.permute(0, 2, 1)).transpose(1, 2)
41
+ return x
42
+
43
+
44
+ class FixedEmbedding(nn.Module):
45
+ def __init__(self, c_in, d_model):
46
+ super(FixedEmbedding, self).__init__()
47
+
48
+ w = torch.zeros(c_in, d_model).float()
49
+ w.require_grad = False
50
+
51
+ position = torch.arange(0, c_in).float().unsqueeze(1)
52
+ div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()
53
+
54
+ w[:, 0::2] = torch.sin(position * div_term)
55
+ w[:, 1::2] = torch.cos(position * div_term)
56
+
57
+ self.emb = nn.Embedding(c_in, d_model)
58
+ self.emb.weight = nn.Parameter(w, requires_grad=False)
59
+
60
+ def forward(self, x):
61
+ return self.emb(x).detach()
62
+
63
+
64
+ class TemporalEmbedding(nn.Module):
65
+ def __init__(self, d_model, embed_type='fixed', freq='h'):
66
+ super(TemporalEmbedding, self).__init__()
67
+
68
+ minute_size = 4
69
+ hour_size = 24
70
+ weekday_size = 7
71
+ day_size = 32
72
+ month_size = 13
73
+
74
+ Embed = FixedEmbedding if embed_type == 'fixed' else nn.Embedding
75
+ if freq == 't':
76
+ self.minute_embed = Embed(minute_size, d_model)
77
+ self.hour_embed = Embed(hour_size, d_model)
78
+ self.weekday_embed = Embed(weekday_size, d_model)
79
+ self.day_embed = Embed(day_size, d_model)
80
+ self.month_embed = Embed(month_size, d_model)
81
+
82
+ def forward(self, x):
83
+ x = x.long()
84
+
85
+ minute_x = self.minute_embed(x[:, :, 4]) if hasattr(self, 'minute_embed') else 0.
86
+ hour_x = self.hour_embed(x[:, :, 3])
87
+ weekday_x = self.weekday_embed(x[:, :, 2])
88
+ day_x = self.day_embed(x[:, :, 1])
89
+ month_x = self.month_embed(x[:, :, 0])
90
+
91
+ return hour_x + weekday_x + day_x + month_x + minute_x
92
+
93
+
94
+ class TimeFeatureEmbedding(nn.Module):
95
+ def __init__(self, d_model, embed_type='timeF', freq='h'):
96
+ super(TimeFeatureEmbedding, self).__init__()
97
+
98
+ freq_map = {'h': 4, 't': 5, 's': 6, 'm': 1, 'a': 1, 'w': 2, 'd': 3, 'b': 3}
99
+ d_inp = freq_map[freq]
100
+ self.embed = nn.Linear(d_inp, d_model, bias=False)
101
+
102
+ def forward(self, x):
103
+ return self.embed(x)
104
+
105
+
106
+ class DataEmbedding(nn.Module):
107
+ def __init__(self, c_in, d_model, embed_type='fixed', freq='h', dropout=0):
108
+ super(DataEmbedding, self).__init__()
109
+
110
+ self.value_embedding = TokenEmbedding(c_in=c_in, d_model=d_model)
111
+ self.position_embedding = PositionalEmbedding(d_model=d_model)
112
+ self.temporal_embedding = TemporalEmbedding(d_model=d_model, embed_type=embed_type,
113
+ freq=freq) if embed_type != 'timeF' else TimeFeatureEmbedding(
114
+ d_model=d_model, embed_type=embed_type, freq=freq)
115
+ self.dropout = nn.Dropout(p=dropout)
116
+
117
+ def forward(self, x, x_mark):
118
+ x = self.value_embedding(x) + self.temporal_embedding(x_mark) + self.position_embedding(x)
119
+ return self.dropout(x)
120
+
121
+
122
+ class DataEmbedding_wo_pos(nn.Module):
123
+ def __init__(self, c_in, d_model, embed_type='fixed', freq='h', dropout=0):
124
+ super(DataEmbedding_wo_pos, self).__init__()
125
+
126
+ self.value_embedding = TokenEmbedding(c_in=c_in, d_model=d_model)
127
+ self.position_embedding = PositionalEmbedding(d_model=d_model)
128
+ self.temporal_embedding = TemporalEmbedding(d_model=d_model, embed_type=embed_type,
129
+ freq=freq) if embed_type != 'timeF' else TimeFeatureEmbedding(
130
+ d_model=d_model, embed_type=embed_type, freq=freq)
131
+ self.dropout = nn.Dropout(p=dropout)
132
+
133
+ def forward(self, x, x_mark):
134
+ x = self.value_embedding(x) + self.temporal_embedding(x_mark)
135
+ return self.dropout(x)
136
+
137
+
138
+ class DataEmbedding_wo_pos_temp(nn.Module):
139
+ def __init__(self, c_in, d_model, embed_type='fixed', freq='h', dropout=0):
140
+ super(DataEmbedding_wo_pos_temp, self).__init__()
141
+
142
+ self.value_embedding = TokenEmbedding(c_in=c_in, d_model=d_model)
143
+ self.position_embedding = PositionalEmbedding(d_model=d_model)
144
+ self.temporal_embedding = TemporalEmbedding(d_model=d_model, embed_type=embed_type,
145
+ freq=freq) if embed_type != 'timeF' else TimeFeatureEmbedding(
146
+ d_model=d_model, embed_type=embed_type, freq=freq)
147
+ self.dropout = nn.Dropout(p=dropout)
148
+
149
+ def forward(self, x, x_mark):
150
+ x = self.value_embedding(x)
151
+ return self.dropout(x)
152
+
153
+
154
+ class DataEmbedding_wo_temp(nn.Module):
155
+ def __init__(self, c_in, d_model, embed_type='fixed', freq='h', dropout=0):
156
+ super(DataEmbedding_wo_temp, self).__init__()
157
+
158
+ self.value_embedding = TokenEmbedding(c_in=c_in, d_model=d_model)
159
+ self.position_embedding = PositionalEmbedding(d_model=d_model)
160
+ self.temporal_embedding = TemporalEmbedding(d_model=d_model, embed_type=embed_type,
161
+ freq=freq) if embed_type != 'timeF' else TimeFeatureEmbedding(
162
+ d_model=d_model, embed_type=embed_type, freq=freq)
163
+ self.dropout = nn.Dropout(p=dropout)
164
+
165
+ def forward(self, x, x_mark):
166
+ x = self.value_embedding(x) + self.position_embedding(x)
167
+ return self.dropout(x)
168
+
169
+
170
+ class TriangularCausalMask():
171
+ def __init__(self, B, L, device="cpu"):
172
+ mask_shape = [B, 1, L, L]
173
+ with torch.no_grad():
174
+ self._mask = torch.triu(torch.ones(mask_shape, dtype=torch.bool), diagonal=1).to(device)
175
+
176
+ @property
177
+ def mask(self):
178
+ return self._mask
179
+
180
+
181
+ class ProbMask():
182
+ def __init__(self, B, H, L, index, scores, device="cpu"):
183
+ _mask = torch.ones(L, scores.shape[-1], dtype=torch.bool).to(device).triu(1)
184
+ _mask_ex = _mask[None, None, :].expand(B, H, L, scores.shape[-1])
185
+ indicator = _mask_ex[torch.arange(B)[:, None, None],
186
+ torch.arange(H)[None, :, None],
187
+ index, :].to(device)
188
+ self._mask = indicator.view(scores.shape).to(device)
189
+
190
+ @property
191
+ def mask(self):
192
+ return self._mask
193
+
194
+
195
+ class FullAttention(nn.Module):
196
+ def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0, output_attention=False):
197
+ super(FullAttention, self).__init__()
198
+ self.scale = scale
199
+ self.mask_flag = mask_flag
200
+ self.output_attention = output_attention
201
+ self.dropout = nn.Dropout(attention_dropout)
202
+
203
+ def forward(self, queries, keys, values, attn_mask):
204
+ B, L, H, E = queries.shape
205
+ _, S, _, D = values.shape
206
+ scale = self.scale or 1. / sqrt(E)
207
+
208
+ scores = torch.einsum("blhe,bshe->bhls", queries, keys)
209
+
210
+ if self.mask_flag:
211
+ if attn_mask is None:
212
+ attn_mask = TriangularCausalMask(B, L, device=queries.device)
213
+
214
+ scores.masked_fill_(attn_mask.mask, -np.inf)
215
+
216
+ A = self.dropout(torch.softmax(scale * scores, dim=-1))
217
+ V = torch.einsum("bhls,bshd->blhd", A, values)
218
+
219
+ if self.output_attention:
220
+ return (V.contiguous(), A)
221
+ else:
222
+ return (V.contiguous(), None)
223
+
224
+
225
+ class ProbAttention(nn.Module):
226
+ def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0, output_attention=False):
227
+ super(ProbAttention, self).__init__()
228
+ self.factor = factor
229
+ self.scale = scale
230
+ self.mask_flag = mask_flag
231
+ self.output_attention = output_attention
232
+ self.dropout = nn.Dropout(attention_dropout)
233
+
234
+ def _prob_QK(self, Q, K, sample_k, n_top): # n_top: c*ln(L_q)
235
+ # Q [B, H, L, D]
236
+ B, H, L_K, E = K.shape
237
+ _, _, L_Q, _ = Q.shape
238
+
239
+ # calculate the sampled Q_K
240
+ K_expand = K.unsqueeze(-3).expand(B, H, L_Q, L_K, E)
241
+ index_sample = torch.randint(L_K, (L_Q, sample_k)) # real U = U_part(factor*ln(L_k))*L_q
242
+ K_sample = K_expand[:, :, torch.arange(L_Q).unsqueeze(1), index_sample, :]
243
+ Q_K_sample = torch.matmul(Q.unsqueeze(-2), K_sample.transpose(-2, -1)).squeeze()
244
+
245
+ # find the Top_k query with sparisty measurement
246
+ M = Q_K_sample.max(-1)[0] - torch.div(Q_K_sample.sum(-1), L_K)
247
+ M_top = M.topk(n_top, sorted=False)[1]
248
+
249
+ # use the reduced Q to calculate Q_K
250
+ Q_reduce = Q[torch.arange(B)[:, None, None],
251
+ torch.arange(H)[None, :, None],
252
+ M_top, :] # factor*ln(L_q)
253
+ Q_K = torch.matmul(Q_reduce, K.transpose(-2, -1)) # factor*ln(L_q)*L_k
254
+
255
+ return Q_K, M_top
256
+
257
+ def _get_initial_context(self, V, L_Q):
258
+ B, H, L_V, D = V.shape
259
+ if not self.mask_flag:
260
+ # V_sum = V.sum(dim=-2)
261
+ V_sum = V.mean(dim=-2)
262
+ contex = V_sum.unsqueeze(-2).expand(B, H, L_Q, V_sum.shape[-1]).clone()
263
+ else: # use mask
264
+ assert (L_Q == L_V) # requires that L_Q == L_V, i.e. for self-attention only
265
+ contex = V.cumsum(dim=-2)
266
+ return contex
267
+
268
+ def _update_context(self, context_in, V, scores, index, L_Q, attn_mask):
269
+ B, H, L_V, D = V.shape
270
+
271
+ if self.mask_flag:
272
+ attn_mask = ProbMask(B, H, L_Q, index, scores, device=V.device)
273
+ scores.masked_fill_(attn_mask.mask, -np.inf)
274
+
275
+ attn = torch.softmax(scores, dim=-1) # nn.Softmax(dim=-1)(scores)
276
+
277
+ context_in[torch.arange(B)[:, None, None],
278
+ torch.arange(H)[None, :, None],
279
+ index, :] = torch.matmul(attn, V).type_as(context_in)
280
+ if self.output_attention:
281
+ attns = (torch.ones([B, H, L_V, L_V]) / L_V).type_as(attn).to(attn.device)
282
+ attns[torch.arange(B)[:, None, None], torch.arange(H)[None, :, None], index, :] = attn
283
+ return (context_in, attns)
284
+ else:
285
+ return (context_in, None)
286
+
287
+ def forward(self, queries, keys, values, attn_mask):
288
+ B, L_Q, H, D = queries.shape
289
+ _, L_K, _, _ = keys.shape
290
+
291
+ queries = queries.transpose(2, 1)
292
+ keys = keys.transpose(2, 1)
293
+ values = values.transpose(2, 1)
294
+
295
+ U_part = self.factor * np.ceil(np.log(L_K)).astype('int').item() # c*ln(L_k)
296
+ u = self.factor * np.ceil(np.log(L_Q)).astype('int').item() # c*ln(L_q)
297
+
298
+ U_part = U_part if U_part < L_K else L_K
299
+ u = u if u < L_Q else L_Q
300
+
301
+ scores_top, index = self._prob_QK(queries, keys, sample_k=U_part, n_top=u)
302
+
303
+ # add scale factor
304
+ scale = self.scale or 1. / sqrt(D)
305
+ if scale is not None:
306
+ scores_top = scores_top * scale
307
+ # get the context
308
+ context = self._get_initial_context(values, L_Q)
309
+ # update the context with selected top_k queries
310
+ context, attn = self._update_context(context, values, scores_top, index, L_Q, attn_mask)
311
+
312
+ return context.contiguous(), attn
313
+
314
+
315
+ class AttentionLayer(nn.Module):
316
+ def __init__(self, attention, d_model, n_heads, d_keys=None,
317
+ d_values=None):
318
+ super(AttentionLayer, self).__init__()
319
+
320
+ d_keys = d_keys or (d_model // n_heads)
321
+ d_values = d_values or (d_model // n_heads)
322
+
323
+ self.inner_attention = attention
324
+ self.query_projection = nn.Linear(d_model, d_keys * n_heads)
325
+ self.key_projection = nn.Linear(d_model, d_keys * n_heads)
326
+ self.value_projection = nn.Linear(d_model, d_values * n_heads)
327
+ self.out_projection = nn.Linear(d_values * n_heads, d_model)
328
+ self.n_heads = n_heads
329
+
330
+ def forward(self, queries, keys, values, attn_mask):
331
+ B, L, _ = queries.shape
332
+ _, S, _ = keys.shape
333
+ H = self.n_heads
334
+
335
+ queries = self.query_projection(queries).view(B, L, H, -1)
336
+ keys = self.key_projection(keys).view(B, S, H, -1)
337
+ values = self.value_projection(values).view(B, S, H, -1)
338
+
339
+ out, attn = self.inner_attention(
340
+ queries,
341
+ keys,
342
+ values,
343
+ attn_mask
344
+ )
345
+ out = out.view(B, L, -1)
346
+
347
+ return self.out_projection(out), attn
348
+
349
+
350
+ class ConvLayer(nn.Module):
351
+ def __init__(self, c_in):
352
+ super(ConvLayer, self).__init__()
353
+ self.downConv = nn.Conv1d(in_channels=c_in,
354
+ out_channels=c_in,
355
+ kernel_size=3,
356
+ padding=2,
357
+ padding_mode='circular')
358
+ self.norm = nn.BatchNorm1d(c_in)
359
+ self.activation = nn.ELU()
360
+ self.maxPool = nn.MaxPool1d(kernel_size=3, stride=2, padding=1)
361
+
362
+ def forward(self, x):
363
+ x = self.downConv(x.permute(0, 2, 1))
364
+ x = self.norm(x)
365
+ x = self.activation(x)
366
+ x = self.maxPool(x)
367
+ x = x.transpose(1, 2)
368
+ return x
369
+
370
+
371
+ class EncoderLayer(nn.Module):
372
+ def __init__(self, attention, d_model, d_ff=None, dropout=0, activation="relu"):
373
+ super(EncoderLayer, self).__init__()
374
+ d_ff = d_ff or 4 * d_model
375
+ self.attention = attention
376
+ self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)
377
+ self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)
378
+ self.norm1 = nn.LayerNorm(d_model)
379
+ self.norm2 = nn.LayerNorm(d_model)
380
+ self.dropout = nn.Dropout(dropout)
381
+ self.activation = F.relu if activation == "relu" else F.gelu
382
+
383
+ def forward(self, x, attn_mask=None):
384
+ new_x, attn = self.attention(
385
+ x, x, x,
386
+ attn_mask=attn_mask
387
+ )
388
+ x = x + self.dropout(new_x)
389
+
390
+ y = x = self.norm1(x)
391
+ y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1))))
392
+ y = self.dropout(self.conv2(y).transpose(-1, 1))
393
+
394
+ return self.norm2(x + y), attn
395
+
396
+
397
+ class Encoder(nn.Module):
398
+ def __init__(self, attn_layers, conv_layers=None, norm_layer=None):
399
+ super(Encoder, self).__init__()
400
+ self.attn_layers = nn.ModuleList(attn_layers)
401
+ self.conv_layers = nn.ModuleList(conv_layers) if conv_layers is not None else None
402
+ self.norm = norm_layer
403
+
404
+ def forward(self, x, attn_mask=None):
405
+ # x [B, L, D]
406
+ attns = []
407
+ if self.conv_layers is not None:
408
+ for attn_layer, conv_layer in zip(self.attn_layers, self.conv_layers):
409
+ x, attn = attn_layer(x, attn_mask=attn_mask)
410
+ x = conv_layer(x)
411
+ attns.append(attn)
412
+ x, attn = self.attn_layers[-1](x)
413
+ attns.append(attn)
414
+ else:
415
+ for attn_layer in self.attn_layers:
416
+ x, attn = attn_layer(x, attn_mask=attn_mask)
417
+ attns.append(attn)
418
+
419
+ if self.norm is not None:
420
+ x = self.norm(x)
421
+
422
+ return x, attns
423
+
424
+
425
+ class DecoderLayer(nn.Module):
426
+ def __init__(self, self_attention, cross_attention, d_model, d_ff=None,
427
+ dropout=0, activation="relu"):
428
+ super(DecoderLayer, self).__init__()
429
+ d_ff = d_ff or 4 * d_model
430
+ self.self_attention = self_attention
431
+ self.cross_attention = cross_attention
432
+ self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=1)
433
+ self.conv2 = nn.Conv1d(in_channels=d_ff, out_channels=d_model, kernel_size=1)
434
+ self.norm1 = nn.LayerNorm(d_model)
435
+ self.norm2 = nn.LayerNorm(d_model)
436
+ self.norm3 = nn.LayerNorm(d_model)
437
+ self.dropout = nn.Dropout(dropout)
438
+ self.activation = F.relu if activation == "relu" else F.gelu
439
+
440
+ def forward(self, x, cross, x_mask=None, cross_mask=None):
441
+ x = x + self.dropout(self.self_attention(
442
+ x, x, x,
443
+ attn_mask=x_mask
444
+ )[0])
445
+ x = self.norm1(x)
446
+
447
+ x = x + self.dropout(self.cross_attention(
448
+ x, cross, cross,
449
+ attn_mask=cross_mask
450
+ )[0])
451
+
452
+ y = x = self.norm2(x)
453
+ y = self.dropout(self.activation(self.conv1(y.transpose(-1, 1))))
454
+ y = self.dropout(self.conv2(y).transpose(-1, 1))
455
+
456
+ return self.norm3(x + y)
457
+
458
+
459
+ class Decoder(nn.Module):
460
+ def __init__(self, layers, norm_layer=None, projection=None):
461
+ super(Decoder, self).__init__()
462
+ self.layers = nn.ModuleList(layers)
463
+ self.norm = norm_layer
464
+ self.projection = projection
465
+
466
+ def forward(self, x, cross, x_mask=None, cross_mask=None):
467
+ for layer in self.layers:
468
+ x = layer(x, cross, x_mask=x_mask, cross_mask=cross_mask)
469
+
470
+ if self.norm is not None:
471
+ x = self.norm(x)
472
+
473
+ if self.projection is not None:
474
+ x = self.projection(x)
475
+ return x
476
+
477
+ class Transformer(nn.Module):
478
+ """
479
+ Vanilla Transformer with O(L^2) complexity
480
+ """
481
+ def __init__(self, enc_in = 2, d_model = 16, n_heads = 2, hidden_size=48, dropout=0, d_ff = 16,
482
+ factor = 1, output_attention = False, enc_layers = 2, activation = 'gelu'):
483
+ super(Transformer, self).__init__()
484
+ self.output_attention = output_attention
485
+
486
+ # Embedding
487
+ self.enc_embedding = DataEmbedding_wo_temp(enc_in,d_model)
488
+ # self.dec_embedding = DataEmbedding_wo_temp(configs.dec_in, configs.d_model)
489
+
490
+ # Encoder
491
+ self.encoder = Encoder(
492
+ [
493
+ EncoderLayer(
494
+ AttentionLayer(
495
+ FullAttention(False, factor, attention_dropout=dropout,
496
+ output_attention=output_attention), d_model, n_heads),
497
+ d_model,
498
+ d_ff,
499
+ dropout = dropout,
500
+ activation = activation
501
+ ) for l in range(enc_layers)
502
+ ],
503
+ norm_layer=torch.nn.LayerNorm(d_model)
504
+ )
505
+ self.GMP = torch.nn.AdaptiveMaxPool1d(1, return_indices=False)
506
+
507
+ # # Decoder
508
+ # self.decoder = Decoder(
509
+ # [
510
+ # DecoderLayer(
511
+ # AttentionLayer(
512
+ # FullAttention(True, configs.factor, attention_dropout=configs.dropout, output_attention=False),
513
+ # configs.d_model, configs.n_heads),
514
+ # AttentionLayer(
515
+ # FullAttention(False, configs.factor, attention_dropout=configs.dropout, output_attention=False),
516
+ # configs.d_model, configs.n_heads),
517
+ # configs.d_model,
518
+ # configs.d_ff,
519
+ # dropout=configs.dropout,
520
+ # activation=configs.activation,
521
+ # )
522
+ # for l in range(configs.d_layers)
523
+ # ],
524
+ # norm_layer=torch.nn.LayerNorm(configs.d_model),
525
+ # projection=nn.Linear(configs.d_model, configs.c_out, bias=True)
526
+ # )
527
+
528
+ def forward(self, x_enc, x_mark_enc=None, x_dec=None, x_mark_dec=None,
529
+ enc_self_mask=None, dec_self_mask=None, dec_enc_mask=None):
530
+
531
+ enc_out = self.enc_embedding(x_enc, x_mark_enc)
532
+ # print(enc_out.shape)
533
+ out, attns = self.encoder(enc_out, attn_mask=enc_self_mask)
534
+ # out [bs, num_node, embedding_dim]
535
+ out = self.GMP(out.permute(0,2,1)).squeeze(-1)
536
+ # dec_out = self.dec_embedding(x_dec, x_mark_dec)
537
+ # dec_out = self.decoder(dec_out, enc_out, x_mask=dec_self_mask, cross_mask=dec_enc_mask)
538
+
539
+ # if self.output_attention:
540
+ # return dec_out[:, -self.pred_len:, :], attns
541
+ # else:
542
+ return out # [B, L, D]
543
+
544
+ if __name__ == '__main__':
545
+ net = Transformer()
546
+ a = torch.randn((1,78,2))
547
+ print(net(a).shape)
scripts/fake_data.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+
8
+
9
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
10
+ sys.path.insert(0, str(PROJECT_ROOT))
11
+
12
+ from onescience.utils.YParams import YParams
13
+
14
+
15
+ def set_default_data_env():
16
+ os.environ.setdefault("ONESCIENCE_BENO_DATA_DIR", str(PROJECT_ROOT / "data"))
17
+
18
+
19
+ def resolve_path(path_value):
20
+ path = Path(path_value)
21
+ return path if path.is_absolute() else PROJECT_ROOT / path
22
+
23
+
24
+ def load_config():
25
+ set_default_data_env()
26
+ cfg = YParams(str(PROJECT_ROOT / "conf" / "config.yaml"), "root")
27
+ cfg.datapipe.source.data_dir = str(resolve_path(cfg.datapipe.source.data_dir))
28
+ cfg.datapipe.source.cache_dir = str(resolve_path(cfg.datapipe.source.cache_dir))
29
+ cfg.fake_data.root_dir = str(resolve_path(cfg.fake_data.root_dir))
30
+ return cfg
31
+
32
+
33
+ def square_boundary(points, boundary_points):
34
+ bottom = [(x, 0.0) for x in points]
35
+ top = [(x, 1.0) for x in points]
36
+ left = [(0.0, y) for y in points[1:-1]]
37
+ right = [(1.0, y) for y in points[1:-1]]
38
+ boundary = np.array(bottom + top + left + right, dtype=np.float64)
39
+ if boundary.shape[0] == 0:
40
+ raise ValueError("resolution is too small to build boundary points")
41
+ repeats = int(math.ceil(boundary_points / boundary.shape[0]))
42
+ return np.tile(boundary, (repeats, 1))[:boundary_points]
43
+
44
+
45
+ def make_beno_arrays(cfg):
46
+ data_cfg = cfg.datapipe.data
47
+ fake_cfg = cfg.fake_data
48
+ total_samples = int(data_cfg.ntrain) + int(data_cfg.ntest)
49
+ resolution = int(data_cfg.resolution)
50
+ boundary_points = int(fake_cfg.boundary_points)
51
+ rng = np.random.default_rng(int(fake_cfg.seed))
52
+
53
+ axis = np.linspace(0.0, 1.0, resolution, dtype=np.float64)
54
+ yy, xx = np.meshgrid(axis, axis, indexing="ij")
55
+ coords = np.stack([xx.reshape(-1), yy.reshape(-1)], axis=-1)
56
+
57
+ cell_state = np.zeros((resolution, resolution), dtype=np.float64)
58
+ cell_state[0, :] = 1.0
59
+ cell_state[-1, :] = 1.0
60
+ cell_state[:, 0] = 1.0
61
+ cell_state[:, -1] = 1.0
62
+ cell_state = cell_state.reshape(-1)
63
+
64
+ boundary_xy = square_boundary(axis, boundary_points)
65
+
66
+ rhs = np.zeros((total_samples, resolution * resolution, 4), dtype=np.float64)
67
+ sol = np.zeros((total_samples, resolution * resolution, 1), dtype=np.float64)
68
+ bc = np.zeros((total_samples, boundary_points, 4), dtype=np.float64)
69
+
70
+ for sample_idx in range(total_samples):
71
+ phase = 0.25 * sample_idx
72
+ amplitude = 1.0 + 0.1 * sample_idx
73
+ forcing = (
74
+ amplitude * np.sin(np.pi * xx + phase) * np.sin(np.pi * yy)
75
+ + 0.15 * np.cos(2.0 * np.pi * xx) * np.sin(np.pi * yy + phase)
76
+ )
77
+ solution = 0.25 * forcing + 0.05 * (xx + yy)
78
+ if fake_cfg.noise_std:
79
+ solution += float(fake_cfg.noise_std) * rng.standard_normal(solution.shape)
80
+
81
+ boundary_value = (
82
+ 0.05 * sample_idx
83
+ + 0.1 * boundary_xy[:, 0]
84
+ - 0.08 * boundary_xy[:, 1]
85
+ )
86
+
87
+ rhs[sample_idx, :, 0:2] = coords
88
+ rhs[sample_idx, :, 2] = forcing.reshape(-1)
89
+ rhs[sample_idx, :, 3] = cell_state
90
+ sol[sample_idx, :, 0] = solution.reshape(-1)
91
+ bc[sample_idx, :, 0:2] = boundary_xy
92
+ bc[sample_idx, :, 2] = boundary_value
93
+
94
+ return rhs, sol, bc
95
+
96
+
97
+ def clear_matching_cache(cfg):
98
+ cache_dir = Path(cfg.datapipe.source.cache_dir)
99
+ prefix = cfg.datapipe.source.file_prefix
100
+ for split, count in (("train", cfg.datapipe.data.ntrain), ("test", cfg.datapipe.data.ntest)):
101
+ cache_file = cache_dir / f"cached_{prefix}_{split}_{count}.pt"
102
+ if cache_file.exists():
103
+ cache_file.unlink()
104
+
105
+
106
+ def main():
107
+ cfg = load_config()
108
+ data_dir = Path(cfg.datapipe.source.data_dir)
109
+ data_dir.mkdir(parents=True, exist_ok=True)
110
+
111
+ rhs, sol, bc = make_beno_arrays(cfg)
112
+ prefix = cfg.datapipe.source.file_prefix
113
+ np.save(data_dir / f"RHS_{prefix}_all.npy", rhs)
114
+ np.save(data_dir / f"SOL_{prefix}_all.npy", sol)
115
+ np.save(data_dir / f"BC_{prefix}_all.npy", bc)
116
+ clear_matching_cache(cfg)
117
+
118
+ print(f"Fake BENO data written to {data_dir}")
119
+ print(f"RHS shape={rhs.shape}, SOL shape={sol.shape}, BC shape={bc.shape}")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ main()
scripts/inference.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+
12
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
13
+ sys.path.insert(0, str(PROJECT_ROOT))
14
+
15
+ from model import HeteroGNS
16
+ from onescience.datapipes.cfd import BENODatapipe
17
+ from onescience.distributed.manager import DistributedManager
18
+ from onescience.utils.YParams import YParams
19
+ from onescience.utils.beno.util import record_data, to_np_array
20
+ from onescience.utils.beno.utilities import LpLoss, plot_data
21
+
22
+
23
+ logging.basicConfig(level=logging.INFO)
24
+ LOGGER = logging.getLogger("BENO_Inference")
25
+
26
+
27
+ def set_default_data_env():
28
+ os.environ.setdefault("ONESCIENCE_BENO_DATA_DIR", str(PROJECT_ROOT / "data"))
29
+
30
+
31
+ def resolve_path(path_value):
32
+ path = Path(path_value)
33
+ return path if path.is_absolute() else PROJECT_ROOT / path
34
+
35
+
36
+ def load_config():
37
+ set_default_data_env()
38
+ cfg = YParams(str(PROJECT_ROOT / "conf" / "config.yaml"), "root")
39
+ cfg.datapipe.source.data_dir = str(resolve_path(cfg.datapipe.source.data_dir))
40
+ cfg.datapipe.source.cache_dir = str(resolve_path(cfg.datapipe.source.cache_dir))
41
+ cfg.inference.checkpoint_dir = str(resolve_path(cfg.inference.checkpoint_dir))
42
+ cfg.inference.result_dir = str(resolve_path(cfg.inference.result_dir))
43
+ cfg.inference.picture_dir = str(resolve_path(cfg.inference.picture_dir))
44
+ cfg.inference.metrics_path = str(resolve_path(cfg.inference.metrics_path))
45
+ if cfg.inference.checkpoint_path:
46
+ cfg.inference.checkpoint_path = str(resolve_path(cfg.inference.checkpoint_path))
47
+ return cfg
48
+
49
+
50
+ def activation_from_name(name):
51
+ name = str(name).lower()
52
+ if name == "relu":
53
+ return nn.ReLU
54
+ if name == "elu":
55
+ return nn.ELU
56
+ if name == "leakyrelu":
57
+ return nn.LeakyReLU
58
+ return nn.SiLU
59
+
60
+
61
+ def build_model(model_cfg):
62
+ return HeteroGNS(
63
+ nnode_in_features=model_cfg.nnode_in_features,
64
+ nnode_out_features=model_cfg.nnode_out_features,
65
+ nedge_in_features=model_cfg.nedge_in_features,
66
+ latent_dim=model_cfg.get("latent_dim", model_cfg.get("width", 128)),
67
+ nmessage_passing_steps=model_cfg.get("nmessage_passing_steps", 10),
68
+ nmlp_layers=model_cfg.nmlp_layers,
69
+ mlp_hidden_dim=model_cfg.get("mlp_hidden_dim", model_cfg.get("width", 128)),
70
+ activation=activation_from_name(model_cfg.act),
71
+ boundary_dim=model_cfg.boundary_dim,
72
+ trans_layer=model_cfg.trans_layer,
73
+ )
74
+
75
+
76
+ def select_device(device_name, dist):
77
+ device_name = str(device_name).lower()
78
+ if device_name == "cpu":
79
+ return torch.device("cpu")
80
+ if device_name == "cuda":
81
+ if not torch.cuda.is_available():
82
+ raise RuntimeError("inference.device is cuda, but CUDA is not available.")
83
+ return torch.device(f"cuda:{dist.local_rank}")
84
+ return dist.device
85
+
86
+
87
+ def find_checkpoint(cfg):
88
+ if cfg.inference.checkpoint_path:
89
+ path = Path(cfg.inference.checkpoint_path)
90
+ return path if path.exists() else None
91
+ checkpoints = sorted(Path(cfg.inference.checkpoint_dir).glob("model_epoch_*.pt"))
92
+ return checkpoints[-1] if checkpoints else None
93
+
94
+
95
+ def main():
96
+ cfg = load_config()
97
+ DistributedManager.initialize()
98
+ dist = DistributedManager()
99
+ device = select_device(cfg.inference.get("device", "auto"), dist)
100
+
101
+ datapipe = BENODatapipe(cfg, distributed=(dist.world_size > 1))
102
+ test_loader, _ = datapipe.test_dataloader()
103
+ u_normalizer = datapipe.u_normalizer.to(device)
104
+ a_normalizer = datapipe.a_normalizer.to(device)
105
+ resolution = int(cfg.datapipe.data.resolution)
106
+
107
+ model = build_model(cfg.model).to(device)
108
+ checkpoint = find_checkpoint(cfg)
109
+ if checkpoint is not None:
110
+ LOGGER.info("Loading checkpoint: %s", checkpoint)
111
+ state_dict = torch.load(checkpoint, map_location=device)
112
+ model.load_state_dict(state_dict)
113
+ else:
114
+ LOGGER.warning("No checkpoint found. Running with random weights.")
115
+ model.eval()
116
+
117
+ result_dir = Path(cfg.inference.result_dir)
118
+ picture_dir = Path(cfg.inference.picture_dir)
119
+ result_dir.mkdir(parents=True, exist_ok=True)
120
+ picture_dir.mkdir(parents=True, exist_ok=True)
121
+
122
+ myloss = LpLoss(size_average=False)
123
+ analysis_record = {}
124
+ out_all = np.array([])
125
+ label_all = np.array([])
126
+ a_ori_all = np.array([])
127
+ mask_all = np.array([])
128
+ grid_all = np.array([])
129
+
130
+ with torch.no_grad():
131
+ for sample_id, data in enumerate(test_loader):
132
+ data = data.to(device)
133
+ out_indomain = model(data)
134
+
135
+ full_out = torch.zeros((resolution * resolution, 1), device=device)
136
+ full_label = torch.zeros((resolution * resolution), device=device)
137
+ full_input_a = torch.zeros((resolution * resolution, 10), device=device)
138
+ full_grid = torch.zeros((resolution * resolution, 2), device=device)
139
+ indices = data["G1"].sample_idx
140
+
141
+ full_out[indices] = out_indomain
142
+ full_label[indices] = data["G1+2"].y
143
+ full_input_a[indices, :] = data["G1"].x
144
+ full_grid[indices, :] = data["G1"].x[:, :2]
145
+
146
+ pred_decoded = u_normalizer.decode(full_out.view(1, -1))
147
+ a_decoded = a_normalizer.decode(full_input_a[:, 2].view(1, -1))
148
+ label_reshaped = full_label.view(1, -1)
149
+
150
+ cell_state_full = torch.zeros((1, resolution * resolution), device=device)
151
+ cell_state_full[0, :] = data["G1"].cell_state
152
+
153
+ l2_item = myloss(pred_decoded, label_reshaped).item()
154
+ mae_item = nn.L1Loss()(pred_decoded, label_reshaped).item()
155
+ record_data(analysis_record, [l2_item, mae_item], ["L2", "MAE"])
156
+
157
+ np.savez(
158
+ result_dir / f"sample_{sample_id:04d}.npz",
159
+ predict=to_np_array(pred_decoded).reshape(resolution, resolution),
160
+ label=to_np_array(label_reshaped).reshape(resolution, resolution),
161
+ forcing=to_np_array(a_decoded).reshape(resolution, resolution),
162
+ mask=to_np_array(cell_state_full).reshape(resolution, resolution),
163
+ )
164
+
165
+ out_all = np.append(out_all, to_np_array(pred_decoded))
166
+ label_all = np.append(label_all, to_np_array(label_reshaped))
167
+ a_ori_all = np.append(a_ori_all, to_np_array(a_decoded))
168
+ mask_all = np.append(mask_all, to_np_array(cell_state_full))
169
+ grid_all = np.append(grid_all, to_np_array(full_grid.unsqueeze(0)))
170
+
171
+ metrics = {
172
+ "mean_l2": float(np.mean(analysis_record["L2"])),
173
+ "std_l2": float(np.std(analysis_record["L2"])),
174
+ "mean_mae": float(np.mean(analysis_record["MAE"])),
175
+ "num_samples": int(len(analysis_record["L2"])),
176
+ }
177
+ metrics_path = Path(cfg.inference.metrics_path)
178
+ metrics_path.parent.mkdir(parents=True, exist_ok=True)
179
+ metrics_path.write_text(json.dumps(metrics, indent=2), encoding="utf-8")
180
+ LOGGER.info("Metrics: %s", metrics)
181
+
182
+ plot_samples = min(int(cfg.inference.num_visualize), metrics["num_samples"])
183
+ if plot_samples >= 2:
184
+ plot_path = picture_dir / "forcing_solution_comparison.png"
185
+ plot_data(
186
+ predict_term=out_all,
187
+ true_term=label_all,
188
+ forcing_term=a_ori_all,
189
+ forcing_mask=mask_all,
190
+ grid_info=grid_all,
191
+ resolution=resolution,
192
+ num_samples=plot_samples,
193
+ interpolation="bilinear",
194
+ save_path=str(plot_path),
195
+ )
196
+ LOGGER.info("Plot saved to %s", plot_path)
197
+ elif plot_samples == 1:
198
+ LOGGER.info("Skipping plot_data for one sample because the runtime helper expects a 2D axes grid.")
199
+
200
+ dist.cleanup()
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()
scripts/result.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+
4
+
5
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
6
+ METRICS_PATH = PROJECT_ROOT / "result" / "metrics.json"
7
+
8
+
9
+ def main():
10
+ if not METRICS_PATH.exists():
11
+ raise FileNotFoundError(f"Missing metrics file: {METRICS_PATH}. Run scripts/inference.py first.")
12
+ metrics = json.loads(METRICS_PATH.read_text(encoding="utf-8"))
13
+ print("BENO inference metrics")
14
+ for key, value in metrics.items():
15
+ print(f"{key}: {value}")
16
+
17
+
18
+ if __name__ == "__main__":
19
+ main()
scripts/train.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ from pathlib import Path
5
+ from timeit import default_timer
6
+
7
+ import numpy as np
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.nn.parallel import DistributedDataParallel as DDP
12
+ from tqdm import tqdm
13
+
14
+
15
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
16
+ sys.path.insert(0, str(PROJECT_ROOT))
17
+
18
+ from model import HeteroGNS
19
+ from onescience.datapipes.cfd import BENODatapipe
20
+ from onescience.distributed.manager import DistributedManager
21
+ from onescience.utils.YParams import YParams
22
+ from onescience.utils.beno.utilities import LpLoss
23
+
24
+
25
+ def set_default_data_env():
26
+ os.environ.setdefault("ONESCIENCE_BENO_DATA_DIR", str(PROJECT_ROOT / "data"))
27
+
28
+
29
+ def resolve_path(path_value):
30
+ path = Path(path_value)
31
+ return path if path.is_absolute() else PROJECT_ROOT / path
32
+
33
+
34
+ def load_config():
35
+ set_default_data_env()
36
+ cfg = YParams(str(PROJECT_ROOT / "conf" / "config.yaml"), "root")
37
+ cfg.datapipe.source.data_dir = str(resolve_path(cfg.datapipe.source.data_dir))
38
+ cfg.datapipe.source.cache_dir = str(resolve_path(cfg.datapipe.source.cache_dir))
39
+ cfg.training.output_dir = str(resolve_path(cfg.training.output_dir))
40
+ return cfg
41
+
42
+
43
+ def seed_everything(seed):
44
+ random.seed(seed)
45
+ np.random.seed(seed)
46
+ torch.manual_seed(seed)
47
+ if torch.cuda.is_available():
48
+ torch.cuda.manual_seed_all(seed)
49
+
50
+
51
+ def activation_from_name(name):
52
+ name = str(name).lower()
53
+ if name == "relu":
54
+ return nn.ReLU
55
+ if name == "elu":
56
+ return nn.ELU
57
+ if name == "leakyrelu":
58
+ return nn.LeakyReLU
59
+ return nn.SiLU
60
+
61
+
62
+ def build_model(model_cfg):
63
+ return HeteroGNS(
64
+ nnode_in_features=model_cfg.nnode_in_features,
65
+ nnode_out_features=model_cfg.nnode_out_features,
66
+ nedge_in_features=model_cfg.nedge_in_features,
67
+ latent_dim=model_cfg.get("latent_dim", model_cfg.get("width", 128)),
68
+ nmessage_passing_steps=model_cfg.get("nmessage_passing_steps", 10),
69
+ nmlp_layers=model_cfg.nmlp_layers,
70
+ mlp_hidden_dim=model_cfg.get("mlp_hidden_dim", model_cfg.get("width", 128)),
71
+ activation=activation_from_name(model_cfg.act),
72
+ boundary_dim=model_cfg.boundary_dim,
73
+ trans_layer=model_cfg.trans_layer,
74
+ )
75
+
76
+
77
+ def select_device(device_name, dist):
78
+ device_name = str(device_name).lower()
79
+ if device_name == "cpu":
80
+ return torch.device("cpu")
81
+ if device_name == "cuda":
82
+ if not torch.cuda.is_available():
83
+ raise RuntimeError("training.device is cuda, but CUDA is not available.")
84
+ return torch.device(f"cuda:{dist.local_rank}")
85
+ return dist.device
86
+
87
+
88
+ def reduce_scalar(value, device, dist):
89
+ tensor = torch.tensor(value, device=device, dtype=torch.float32)
90
+ if dist.world_size > 1:
91
+ torch.distributed.all_reduce(tensor)
92
+ tensor /= dist.world_size
93
+ return tensor.item()
94
+
95
+
96
+ def evaluate(model, test_loader, device, u_normalizer, myloss, dist):
97
+ model.eval()
98
+ total_l2 = 0.0
99
+ with torch.no_grad():
100
+ for batch in test_loader:
101
+ batch = batch.to(device)
102
+ out = model(batch)
103
+ pred = u_normalizer.decode(
104
+ out.view(batch.num_graphs, -1),
105
+ sample_idx=batch["G1"].sample_idx.view(batch.num_graphs, -1),
106
+ )
107
+ total_l2 += myloss(pred, batch["G1+2"].y.view(batch.num_graphs, -1)).item()
108
+ total_l2 = reduce_scalar(total_l2, device, dist)
109
+ return total_l2
110
+
111
+
112
+ def main():
113
+ cfg = load_config()
114
+ seed_everything(int(cfg.training.seed))
115
+
116
+ DistributedManager.initialize()
117
+ dist = DistributedManager()
118
+ device = select_device(cfg.training.get("device", "auto"), dist)
119
+
120
+ output_dir = Path(cfg.training.output_dir)
121
+ if dist.rank == 0:
122
+ output_dir.mkdir(parents=True, exist_ok=True)
123
+ print(f"Config: {PROJECT_ROOT / 'conf' / 'config.yaml'}")
124
+ print(f"Data: {cfg.datapipe.source.data_dir}")
125
+ print(f"Checkpoint directory: {output_dir}")
126
+
127
+ datapipe = BENODatapipe(cfg, distributed=(dist.world_size > 1))
128
+ train_loader, train_sampler = datapipe.train_dataloader()
129
+ test_loader, _ = datapipe.test_dataloader()
130
+ if len(train_loader) == 0:
131
+ raise RuntimeError("Training loader is empty. Check ntrain and batch_size.")
132
+
133
+ u_normalizer = datapipe.u_normalizer.to(device)
134
+ model = build_model(cfg.model).to(device)
135
+ if dist.world_size > 1:
136
+ device_ids = [dist.local_rank] if device.type == "cuda" else None
137
+ model = DDP(model, device_ids=device_ids)
138
+
139
+ optimizer = torch.optim.Adam(
140
+ model.parameters(),
141
+ lr=cfg.training.optimizer.lr,
142
+ weight_decay=cfg.training.optimizer.weight_decay,
143
+ )
144
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(
145
+ optimizer,
146
+ T_0=cfg.training.scheduler.T_0,
147
+ T_mult=cfg.training.scheduler.T_mult,
148
+ )
149
+ myloss = LpLoss(size_average=False)
150
+
151
+ for epoch in range(int(cfg.training.epochs)):
152
+ if train_sampler:
153
+ train_sampler.set_epoch(epoch)
154
+
155
+ model.train()
156
+ train_mse = 0.0
157
+ train_l2 = 0.0
158
+ batches = 0
159
+ start = default_timer()
160
+ iterator = tqdm(train_loader, desc=f"Epoch {epoch}", disable=(dist.rank != 0))
161
+
162
+ for batch in iterator:
163
+ batch = batch.to(device)
164
+ optimizer.zero_grad(set_to_none=True)
165
+ out = model(batch)
166
+ loss = F.mse_loss(out.view(-1, 1), batch["G1+2"].y.view(-1, 1))
167
+ loss.backward()
168
+ optimizer.step()
169
+
170
+ with torch.no_grad():
171
+ pred_denorm = u_normalizer.decode(
172
+ out.view(batch.num_graphs, -1),
173
+ sample_idx=batch["G1"].sample_idx.view(batch.num_graphs, -1),
174
+ )
175
+ target_denorm = u_normalizer.decode(
176
+ batch["G1+2"].y.view(batch.num_graphs, -1),
177
+ sample_idx=batch["G1"].sample_idx.view(batch.num_graphs, -1),
178
+ )
179
+ l2 = myloss(pred_denorm, target_denorm)
180
+
181
+ train_mse += loss.item()
182
+ train_l2 += l2.item()
183
+ batches += 1
184
+ if dist.rank == 0:
185
+ iterator.set_postfix({"mse": f"{loss.item():.2e}", "l2": f"{l2.item():.2e}"})
186
+
187
+ scheduler.step()
188
+ train_mse = reduce_scalar(train_mse / batches, device, dist)
189
+ train_l2 = reduce_scalar(train_l2 / datapipe.train_dataset.ntrain, device, dist)
190
+ test_l2 = evaluate(model, test_loader, device, u_normalizer, myloss, dist)
191
+ test_l2 /= datapipe.test_dataset.ntest
192
+
193
+ if dist.rank == 0:
194
+ print(
195
+ f"Epoch {epoch:03d} | Train MSE: {train_mse:.6f} | "
196
+ f"Train L2: {train_l2:.6f} | Test L2: {test_l2:.6f} | "
197
+ f"Time: {default_timer() - start:.1f}s"
198
+ )
199
+ if (epoch + 1) % int(cfg.training.save_period) == 0:
200
+ model_to_save = model.module if hasattr(model, "module") else model
201
+ checkpoint_name = cfg.training.checkpoint_name.format(epoch=epoch)
202
+ ckpt_path = output_dir / checkpoint_name
203
+ torch.save(model_to_save.state_dict(), ckpt_path)
204
+ print(f"Saved checkpoint to {ckpt_path}")
205
+
206
+ dist.cleanup()
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()