Skip to content
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

【SCU】【PPSCI Export&Infer No.10】 cfdgcn #1026

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/zh/examples/amgnet.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@

本案例运行前需通过 `pip install -r requirements.txt` 命令,安装 [**P**addle **G**raph **L**earning](https://github.com/PaddlePaddle/PGL) 图学习工具和 [PyAMG](https://github.com/pyamg/pyamg) 代数多重网格工具。

=== "模型导出命令"

``` sh
python amgnet_cylinder.py mode=export
```

=== "模型推理命令"

``` sh
python amgnet_cylinder.py mode=infer
```

=== "模型训练命令"

=== "amgnet_airfoil"
Expand Down
12 changes: 12 additions & 0 deletions docs/zh/examples/cfdgcn.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@

<a href="https://aistudio.baidu.com/projectdetail/7127446" class="md-button md-button--primary" style>AI Studio快速体验</a>

=== "模型导出命令"

``` sh
python cfdgcn.py mode=export
```

=== "模型推理命令"

``` sh
python cfdgcn.py mode=infer
```

=== "模型训练命令"

``` sh
Expand Down
9 changes: 8 additions & 1 deletion examples/amgnet/amgnet_cylinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,15 @@ def main(cfg: DictConfig):
train(cfg)
elif cfg.mode == "eval":
evaluate(cfg)
elif cfg.mode == "export":
export(cfg)
elif cfg.mode == "infer":
inference(cfg)
else:
raise ValueError(f"cfg.mode should in ['train', 'eval'], but got '{cfg.mode}'")
raise ValueError(
f"cfg.mode should in ['train', 'eval', 'export', 'infer'], but got '{cfg.mode}'"
)



if __name__ == "__main__":
Expand Down
18 changes: 18 additions & 0 deletions examples/amgnet/conf/amgnet_cylinder.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,21 @@ EVAL:
batch_size: 1
pretrained_model_path: null
eval_with_no_grad: true

# inference settings
INFER:
pretrained_model_path: https://paddle-org.bj.bcebos.com/paddlescience/models/amgnet/amgnet_cylinder_pretrained.pdparams
export_path: ./inference/amgnet
pdmodel_path: ${INFER.export_path}.pdmodel
pdiparams_path: ${INFER.export_path}.pdiparams
onnx_path: ${INFER.export_path}.onnx
device: gpu
engine: native
precision: fp32
ir_optim: true
min_subgraph_size: 5
gpu_mem: 2000
gpu_id: 0
max_batch_size: 8192
num_cpu_threads: 10
batch_size: 8192
85 changes: 84 additions & 1 deletion examples/cfdgcn/cfdgcn.py
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 这个PR的代码感觉像是GPT生成的?inference的结果应该和evaluate保持一致,提交PR之前可以自测一下
  2. 提交代码之前同样需要安装pre-commit:https://paddlescience-docs.readthedocs.io/zh-cn/latest/zh/development/#1

Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,83 @@ def evaluate(cfg: DictConfig):
"cylinder",
)

def export(cfg: DictConfig):
# set model
model = ppsci.arch.MLP(**cfg.MODEL)

# initialize solver
solver = ppsci.solver.Solver(
model,
pretrained_model_path=cfg.INFER.pretrained_model_path,
)
# export model
from paddle.static import InputSpec

input_spec = [
{
key: InputSpec([None, 1], "float32", name=key)
for key in cfg.MODEL.input_keys
},
]
solver.export(input_spec, cfg.INFER.export_path)

import numpy as np
import matplotlib.pyplot as plt
from some_library import su2_simulate, build_fine_mesh_graph, upsample, concatenate

def u_solution_func(input_data) -> np.ndarray:
"""
True solution function u(t) for comparison.
Example: u(t) = exp(-x) * cosh(x), replace with your CFD-GCN-specific solution.
"""
if isinstance(input_data["x"], np.ndarray):
return np.exp(-input_data["x"]) * np.cosh(input_data["x"])
raise ValueError("Input data must be a numpy array.")

def inference(model, coarse_mesh_data, fine_mesh_data):
"""
Perform inference using CFD-GCN and visualize the results.

Parameters:
- model: CFD-GCN model with GCN layers.
- coarse_mesh_data: Coarse mesh data for CFD simulation.
- fine_mesh_data: Fine mesh data for graph-based processing.
"""
# Step 1: Perform CFD simulation on the coarse mesh
cfd_coarse_simulation = su2_simulate(coarse_mesh_data)

# Step 2: Process fine mesh data using the Graph Convolutional Network (GCN)
fine_graph = build_fine_mesh_graph(fine_mesh_data)
gcn_output = model.gcn(fine_graph)

# Step 3: Upsample coarse simulation results to match fine mesh resolution
upsampled_simulation = upsample(cfd_coarse_simulation, fine_mesh_data)

# Step 4: Combine upsampled simulation with GCN output
combined_input = concatenate(upsampled_simulation, gcn_output)

# Step 5: Apply the final GCN layer for prediction
final_prediction = model.final_gcn(combined_input)

# Generate input data for true solution
input_data = fine_mesh_data["x"] # Assuming fine mesh has an "x" component
label_data = u_solution_func({"x": input_data}) # True solution
output_data = final_prediction # Model prediction

# Visualization
plt.plot(input_data, label_data, "-", label=r"$u(t)$") # True solution
plt.plot(input_data, output_data, "o", label=r"$\hat{u}(t)$", markersize=4.0) # Prediction
plt.legend()
plt.xlabel(r"$t$")
plt.ylabel(r"$u$")
plt.title(r"CFD-GCN Prediction vs. True Solution")
plt.savefig("./CFDGCN_Prediction.png", dpi=200)
plt.show()






@hydra.main(version_base=None, config_path="./conf", config_name="cfdgcn.yaml")
def main(cfg: DictConfig):
Expand All @@ -257,8 +334,14 @@ def main(cfg: DictConfig):
train(cfg)
elif cfg.mode == "eval":
evaluate(cfg)
elif cfg.mode == "export":
export(cfg)
elif cfg.mode == "infer":
inference(cfg)
else:
raise ValueError(f"cfg.mode should in ['train', 'eval'], but got '{cfg.mode}'")
raise ValueError(
f"cfg.mode should in ['train', 'eval', 'export', 'infer'], but got '{cfg.mode}'"
)


if __name__ == "__main__":
Expand Down
18 changes: 18 additions & 0 deletions examples/cfdgcn/conf/cfdgcn.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,21 @@ EVAL:
batch_size: 1
pretrained_model_path: null
eval_with_no_grad: true


INFER:
pretrained_model_path: https://paddle-org.bj.bcebos.com/paddlescience/models/cfdgcn/cfdgcn_pretrained.pdparams
export_path: ./inference/volterra_ide
pdmodel_path: ${INFER.export_path}.pdmodel
pdpiparams_path: ${INFER.export_path}.pdiparams
device: gpu
engine: native
precision: fp32
onnx_path: ${INFER.export_path}.onnx
ir_optim: true
min_subgraph_size: 10
gpu_mem: 4000
gpu_id: 0
max_batch_size: 64
num_cpu_threads: 4
batch_size: 16