-
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
【PPSCI Export&Infer No. 29】 add export and inference #793
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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 | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
@@ -13,6 +13,7 @@ | |||||||||
# limitations under the License. | ||||||||||
|
||||||||||
from os import path as osp | ||||||||||
from typing import Dict | ||||||||||
|
||||||||||
import functions as func_module | ||||||||||
import h5py | ||||||||||
|
@@ -120,7 +121,7 @@ def evaluate(cfg: DictConfig): | |||||||||
|
||||||||||
# fixed iteration stop times for evaluation | ||||||||||
iterations_stop_times = range(5, 85, 5) | ||||||||||
model = TopOptNN() | ||||||||||
model = TopOptNN(**cfg.MODEL) | ||||||||||
|
||||||||||
# evaluation for 4 cases | ||||||||||
acc_results_summary = {} | ||||||||||
|
@@ -317,14 +318,131 @@ def val_metric(output_dict, label_dict, weight_dict=None): | |||||||||
return {"Binary_Acc": acc, "IoU": iou} | ||||||||||
|
||||||||||
|
||||||||||
# export model | ||||||||||
def export(cfg: DictConfig): | ||||||||||
# set model | ||||||||||
model = TopOptNN(**cfg.MODEL) | ||||||||||
|
||||||||||
# initialize solver | ||||||||||
solver = ppsci.solver.Solver( | ||||||||||
model, | ||||||||||
eval_with_no_grad=True, | ||||||||||
pretrained_model_path=cfg.INFER.pretrained_model_path_dict[ | ||||||||||
cfg.INFER.pretrained_model_name | ||||||||||
], | ||||||||||
) | ||||||||||
|
||||||||||
# export model | ||||||||||
from paddle.static import InputSpec | ||||||||||
|
||||||||||
input_spec = [{"input": InputSpec([None, 2, 40, 40], "float32", name="input")}] | ||||||||||
|
||||||||||
solver.export(input_spec, cfg.INFER.export_path) | ||||||||||
|
||||||||||
|
||||||||||
def inference(cfg: DictConfig): | ||||||||||
# read h5 data | ||||||||||
h5data = h5py.File(cfg.DATA_PATH, "r") | ||||||||||
data_iters = np.array(h5data["iters"]) | ||||||||||
data_targets = np.array(h5data["targets"]) | ||||||||||
idx = np.random.choice(len(data_iters), cfg.INFER.img_num, False) | ||||||||||
data_iters = data_iters[idx] | ||||||||||
data_targets = data_targets[idx] | ||||||||||
|
||||||||||
sampler = func_module.generate_sampler(cfg.INFER.sampler_key, cfg.INFER.sampler_num) | ||||||||||
data_iters = channel_sampling(sampler, data_iters) | ||||||||||
|
||||||||||
from deploy.python_infer import pinn_predictor | ||||||||||
|
||||||||||
predictor = pinn_predictor.PINNPredictor(cfg) | ||||||||||
|
||||||||||
input_dict = {"input": data_iters} | ||||||||||
output_dict = predictor.predict(input_dict, cfg.INFER.batch_size) | ||||||||||
|
||||||||||
# mapping data to output_key | ||||||||||
output_dict = { | ||||||||||
store_key: output_dict[infer_key] | ||||||||||
for store_key, infer_key in zip({"output"}, output_dict.keys()) | ||||||||||
} | ||||||||||
|
||||||||||
save_topopt_img( | ||||||||||
input_dict, | ||||||||||
output_dict, | ||||||||||
data_targets, | ||||||||||
cfg.INFER.save_res_path, | ||||||||||
cfg.INFER.res_img_figsize, | ||||||||||
cfg.INFER.save_npy, | ||||||||||
) | ||||||||||
|
||||||||||
|
||||||||||
# used for inference | ||||||||||
def channel_sampling(sampler, input): | ||||||||||
SIMP_initial_iter_time = sampler() | ||||||||||
input_channel_k = input[:, SIMP_initial_iter_time, :, :] | ||||||||||
input_channel_k_minus_1 = input[:, SIMP_initial_iter_time - 1, :, :] | ||||||||||
input = np.stack( | ||||||||||
(input_channel_k, input_channel_k - input_channel_k_minus_1), axis=1 | ||||||||||
) | ||||||||||
return input | ||||||||||
|
||||||||||
|
||||||||||
# used for inference | ||||||||||
def save_topopt_img( | ||||||||||
input_dict: Dict[str, np.ndarray], | ||||||||||
output_dict: Dict[str, np.ndarray], | ||||||||||
ground_truth: np.ndarray, | ||||||||||
save_dir: str, | ||||||||||
figsize: tuple = None, | ||||||||||
save_npy: bool = False, | ||||||||||
): | ||||||||||
|
||||||||||
input = input_dict["input"] | ||||||||||
output = output_dict["output"] | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 保存前先创建文件夹,否则会报错
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 已修改 |
||||||||||
import os | ||||||||||
|
||||||||||
import matplotlib.pyplot as plt | ||||||||||
|
||||||||||
os.makedirs(save_dir, exist_ok=True) | ||||||||||
for i in range(len(input)): | ||||||||||
plt.figure(figsize=figsize) | ||||||||||
plt.subplot(1, 4, 1) | ||||||||||
plt.axis("off") | ||||||||||
plt.imshow(input[i][0], cmap="gray") | ||||||||||
plt.title("Input Image") | ||||||||||
plt.subplot(1, 4, 2) | ||||||||||
plt.axis("off") | ||||||||||
plt.imshow(input[i][1], cmap="gray") | ||||||||||
plt.title("Input Gradient") | ||||||||||
plt.subplot(1, 4, 3) | ||||||||||
plt.axis("off") | ||||||||||
plt.imshow(np.round(output[i][0]), cmap="gray") | ||||||||||
plt.title("Prediction") | ||||||||||
plt.subplot(1, 4, 4) | ||||||||||
plt.axis("off") | ||||||||||
plt.imshow(np.round(ground_truth[i][0]), cmap="gray") | ||||||||||
plt.title("Ground Truth") | ||||||||||
plt.show() | ||||||||||
plt.savefig(osp.join(save_dir, f"Prediction_{i}.png")) | ||||||||||
plt.close() | ||||||||||
if save_npy: | ||||||||||
with open(osp(save_dir, f"Prediction_{i}.npy"), "wb") as f: | ||||||||||
np.save(f, output[i]) | ||||||||||
|
||||||||||
|
||||||||||
@hydra.main(version_base=None, config_path="./conf", config_name="topopt.yaml") | ||||||||||
def main(cfg: DictConfig): | ||||||||||
if cfg.mode == "train": | ||||||||||
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__": | ||||||||||
|
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
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.
是否可以以注释的形式补充另外几个Poisson系列的模型呢?模型推理命令同
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.
已修改