-
Notifications
You must be signed in to change notification settings - Fork 165
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Example] Add AMGNet example #549
Merged
zhiminzhang0830
merged 29 commits into
PaddlePaddle:develop
from
HydrogenSulfate:add_AMGNet
Oct 23, 2023
Merged
Changes from 16 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
de89025
update WIP code
HydrogenSulfate 38659ca
(WIP)update AMGNet code
HydrogenSulfate 24d4d09
try import pgl to avoid importerror
HydrogenSulfate f1bd744
try import pyamg to avoid importerror
HydrogenSulfate 83f707c
add airfoil_dataset.py
HydrogenSulfate e770842
add type checking for amgnet
HydrogenSulfate e773e20
try import pgl to avoid importerror
HydrogenSulfate fa2adda
refine Timer
HydrogenSulfate c524a27
replace pgl.Dataset with io.Dataset
HydrogenSulfate 66954a6
update reproded code
HydrogenSulfate ac13693
replace ImportError with ModuleNotFoundError
HydrogenSulfate f0ae844
refine amgnet.py
HydrogenSulfate 283301c
refine amgnet_airfoil.py and amgnet_cylinder.py
HydrogenSulfate 8fee479
refine utils.py
HydrogenSulfate f242756
refine collate_fn
HydrogenSulfate 031f210
fix bug in eval.py
HydrogenSulfate 781d217
refine codes
HydrogenSulfate 2b8b754
refine codes
HydrogenSulfate c3e560a
modify atol from 1e-8 to 1e-7 of UT test_navierstokes
HydrogenSulfate 997fa3f
refine code
HydrogenSulfate 3a6e985
add AMGNet document
HydrogenSulfate d593755
fix
HydrogenSulfate 11c803d
fix
HydrogenSulfate 2381290
avoid tensor converion in dataset, and move in to collate_fn
HydrogenSulfate a59bc28
Merge branch 'develop' into add_AMGNet
HydrogenSulfate 7eb4aab
update final code
HydrogenSulfate 876ef4d
add example for AMGNet
HydrogenSulfate 9c04c5b
fix doc
HydrogenSulfate a55ae30
Merge branch 'develop' into add_AMGNet
HydrogenSulfate File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. | ||
|
||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
|
||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING | ||
from typing import Dict | ||
from typing import List | ||
|
||
import utils | ||
from paddle.nn import functional as F | ||
|
||
import ppsci | ||
from ppsci.utils import config | ||
from ppsci.utils import logger | ||
|
||
if TYPE_CHECKING: | ||
import paddle | ||
import pgl | ||
|
||
|
||
def train_mse_func( | ||
output_dict: Dict[str, "paddle.Tensor"], label_dict: Dict[str, "pgl.Graph"], *args | ||
) -> paddle.Tensor: | ||
return F.mse_loss(output_dict["pred"], label_dict["label"].y) | ||
|
||
|
||
def eval_rmse_func( | ||
output_dict: Dict[str, List["paddle.Tensor"]], | ||
label_dict: Dict[str, List["pgl.Graph"]], | ||
*args, | ||
) -> Dict[str, float]: | ||
mse_losses = [ | ||
F.mse_loss(pred, label.y) | ||
for (pred, label) in zip(output_dict["pred"], label_dict["label"]) | ||
] | ||
return {"RMSE": (sum(mse_losses) / len(mse_losses)) ** 0.5} | ||
|
||
|
||
if __name__ == "__main__": | ||
args = config.parse_args() | ||
# set random seed for reproducibility | ||
ppsci.utils.misc.set_random_seed(42) | ||
# set output directory | ||
OUTPUT_DIR = "./output_AMGNet" if not args.output_dir else args.output_dir | ||
# initialize logger | ||
logger.init_logger("ppsci", f"{OUTPUT_DIR}/train.log", "info") | ||
|
||
# set airfoil model | ||
model = ppsci.arch.AMGNet( | ||
input_dim=5, | ||
output_dim=3, | ||
latent_dim=128, | ||
num_layers=2, | ||
message_passing_aggregator="sum", | ||
message_passing_steps=6, | ||
speed="norm", | ||
) | ||
|
||
# set dataloader config | ||
ITERS_PER_EPOCH = 42 | ||
train_dataloader_cfg = { | ||
"dataset": { | ||
"name": "MeshAirfoilDataset", | ||
"input_keys": ("input",), | ||
"label_keys": ("label",), | ||
"data_root": "./data/NACA0012_interpolate/outputs_train", | ||
"mesh_graph_path": "./data/NACA0012_interpolate/mesh_fine.su2", | ||
}, | ||
"batch_size": 4, | ||
"sampler": { | ||
"name": "BatchSampler", | ||
"drop_last": False, | ||
"shuffle": True, | ||
}, | ||
"num_workers": 1, | ||
} | ||
|
||
# set constraint | ||
sup_constraint = ppsci.constraint.SupervisedConstraint( | ||
train_dataloader_cfg, | ||
output_expr={"pred": lambda out: out["pred"]}, | ||
loss=ppsci.loss.FunctionalLoss(train_mse_func), | ||
name="Sup", | ||
) | ||
# wrap constraints together | ||
constraint = {sup_constraint.name: sup_constraint} | ||
|
||
# set training hyper-parameters | ||
EPOCHS = 500 if not args.epochs else args.epochs | ||
|
||
# set optimizer | ||
optimizer = ppsci.optimizer.Adam(5e-4)(model) | ||
|
||
# set validator | ||
eval_dataloader_cfg = { | ||
"dataset": { | ||
"name": "MeshAirfoilDataset", | ||
"input_keys": ("input",), | ||
"label_keys": ("label",), | ||
"data_root": "./data/NACA0012_interpolate/outputs_test", | ||
"mesh_graph_path": "./data/NACA0012_interpolate/mesh_fine.su2", | ||
}, | ||
"batch_size": 1, | ||
"sampler": { | ||
"name": "BatchSampler", | ||
"drop_last": False, | ||
"shuffle": False, | ||
}, | ||
} | ||
rmse_validator = ppsci.validate.SupervisedValidator( | ||
eval_dataloader_cfg, | ||
loss=ppsci.loss.FunctionalLoss(train_mse_func), | ||
output_expr={"pred": lambda out: out["pred"]}, | ||
metric={"RMSE": ppsci.metric.FunctionalMetric(eval_rmse_func)}, | ||
name="RMSE_validator", | ||
) | ||
validator = {rmse_validator.name: rmse_validator} | ||
|
||
# initialize solver | ||
solver = ppsci.solver.Solver( | ||
model, | ||
constraint, | ||
OUTPUT_DIR, | ||
optimizer, | ||
None, | ||
EPOCHS, | ||
ITERS_PER_EPOCH, | ||
save_freq=50, | ||
eval_during_train=True, | ||
eval_freq=50, | ||
validator=validator, | ||
eval_with_no_grad=True, | ||
) | ||
# train model | ||
solver.train() | ||
|
||
# visualize prediction | ||
with solver.no_grad_context_manager(True): | ||
for index, batch in enumerate(rmse_validator.data_loader): | ||
truefield = batch[0]["input"].y | ||
prefield = model(batch[0]) | ||
utils.log_images( | ||
batch[0]["input"].pos, | ||
prefield["pred"], | ||
truefield, | ||
rmse_validator.data_loader.dataset.elems_list, | ||
"test", | ||
index, | ||
flag="airfoil", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,162 @@ | ||
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. | ||
|
||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
|
||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING | ||
from typing import Dict | ||
from typing import List | ||
|
||
import utils | ||
from paddle.nn import functional as F | ||
|
||
import ppsci | ||
from ppsci.utils import config | ||
from ppsci.utils import logger | ||
|
||
if TYPE_CHECKING: | ||
import paddle | ||
import pgl | ||
|
||
|
||
def train_mse_func( | ||
output_dict: Dict[str, "paddle.Tensor"], label_dict: Dict[str, "pgl.Graph"], *args | ||
) -> paddle.Tensor: | ||
return F.mse_loss(output_dict["pred"], label_dict["label"].y) | ||
|
||
|
||
def eval_rmse_func( | ||
output_dict: Dict[str, List["paddle.Tensor"]], | ||
label_dict: Dict[str, List["pgl.Graph"]], | ||
*args, | ||
) -> Dict[str, float]: | ||
mse_losses = [ | ||
F.mse_loss(pred, label.y) | ||
for (pred, label) in zip(output_dict["pred"], label_dict["label"]) | ||
] | ||
return {"RMSE": (sum(mse_losses) / len(mse_losses)) ** 0.5} | ||
|
||
|
||
if __name__ == "__main__": | ||
args = config.parse_args() | ||
# set random seed for reproducibility | ||
ppsci.utils.misc.set_random_seed(42) | ||
# set output directory | ||
OUTPUT_DIR = "./output_AMGNet_Cylinder" if not args.output_dir else args.output_dir | ||
# initialize logger | ||
logger.init_logger("ppsci", f"{OUTPUT_DIR}/train.log", "info") | ||
|
||
# set cylinder model | ||
model = ppsci.arch.AMGNet( | ||
input_dim=4, | ||
output_dim=3, | ||
latent_dim=128, | ||
num_layers=2, | ||
message_passing_aggregator="sum", | ||
message_passing_steps=6, | ||
speed="norm", | ||
) | ||
|
||
# set dataloader config | ||
ITERS_PER_EPOCH = 42 | ||
train_dataloader_cfg = { | ||
"dataset": { | ||
"name": "MeshCylinderDataset", | ||
"input_keys": ("input",), | ||
"label_keys": ("label",), | ||
"data_root": "./data/cylinderdata/train", | ||
"mesh_graph_path": "./data/cylinderdata/cylinder.su2", | ||
}, | ||
"batch_size": 4, | ||
"sampler": { | ||
"name": "BatchSampler", | ||
"drop_last": False, | ||
"shuffle": True, | ||
}, | ||
"num_workers": 1, | ||
} | ||
|
||
# set constraint | ||
sup_constraint = ppsci.constraint.SupervisedConstraint( | ||
train_dataloader_cfg, | ||
output_expr={"pred": lambda out: out["pred"]}, | ||
loss=ppsci.loss.FunctionalLoss(train_mse_func), | ||
name="Sup", | ||
) | ||
# wrap constraints together | ||
constraint = {sup_constraint.name: sup_constraint} | ||
|
||
# set training hyper-parameters | ||
EPOCHS = 500 if not args.epochs else args.epochs | ||
|
||
# set optimizer | ||
optimizer = ppsci.optimizer.Adam(5e-4)(model) | ||
|
||
# set validator | ||
eval_dataloader_cfg = { | ||
"dataset": { | ||
"name": "MeshCylinderDataset", | ||
"input_keys": ("input",), | ||
"label_keys": ("label",), | ||
"data_root": "./data/cylinderdata/test", | ||
"mesh_graph_path": "./data/cylinderdata/cylinder.su2", | ||
}, | ||
"batch_size": 1, | ||
"sampler": { | ||
"name": "BatchSampler", | ||
"drop_last": False, | ||
"shuffle": False, | ||
}, | ||
} | ||
rmse_validator = ppsci.validate.SupervisedValidator( | ||
eval_dataloader_cfg, | ||
loss=ppsci.loss.FunctionalLoss(train_mse_func), | ||
output_expr={"pred": lambda out: out["pred"]}, | ||
metric={"RMSE": ppsci.metric.FunctionalMetric(eval_rmse_func)}, | ||
name="RMSE_validator", | ||
) | ||
validator = {rmse_validator.name: rmse_validator} | ||
|
||
# initialize solver | ||
solver = ppsci.solver.Solver( | ||
model, | ||
constraint, | ||
OUTPUT_DIR, | ||
optimizer, | ||
None, | ||
EPOCHS, | ||
ITERS_PER_EPOCH, | ||
save_freq=50, | ||
eval_during_train=True, | ||
eval_freq=50, | ||
validator=validator, | ||
eval_with_no_grad=True, | ||
) | ||
# train model | ||
solver.train() | ||
|
||
# visualize prediction | ||
with solver.no_grad_context_manager(True): | ||
for index, batch in enumerate(rmse_validator.data_loader): | ||
truefield = batch[0]["input"].y | ||
prefield = model(batch[0]) | ||
utils.log_images( | ||
batch[0]["input"].pos, | ||
prefield["pred"], | ||
truefield, | ||
rmse_validator.data_loader.dataset.elems_list, | ||
"test", | ||
index, | ||
flag="cylinder", | ||
) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个可以去掉吧
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
这个None参数属于位置参数,不能删除,删了的话代码行数会变动