Download scripts/result.py from OneScience-Group/SirenFNO: direct link, hf CLI and curl.
- Browser
- Download file 9.92 kB
-
https://huggingface.co/OneScience-Group/SirenFNO/resolve/main/scripts/result.py
- Command line
-
hf download hf://OneScience-Group/SirenFNO/scripts/result.py
-
curl -L -o result.py https://huggingface.co/OneScience-Group/SirenFNO/resolve/main/scripts/result.py
9.92 kB
| """Plot real saved inference fields and summarize the completed experiment.""" | |
| import csv | |
| import json | |
| from pathlib import Path | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import torch | |
| from common import arguments, atomic_json, load_config, relative_l2, sha256 | |
| def main(): | |
| args = arguments(__doc__).parse_args() | |
| config = load_config(args.config) | |
| root = Path(config["output"]["root"]) | |
| results = root / config["output"]["results"] | |
| metrics = json.loads((results / "metrics.json").read_text()) | |
| saved = torch.load(results / "predictions.pt", map_location="cpu", weights_only=False) | |
| assert saved["checkpoint_sha256"] == metrics["checkpoint_sha256"] | |
| assert metrics["checkpoint_sha256"] == sha256(metrics["checkpoint"]) | |
| assert saved["prediction"].shape == saved["y"].shape == (200, 1, 32, 32) | |
| errors = relative_l2(saved["prediction"].double(), saved["y"].double()).numpy() | |
| assert np.isfinite(errors).all() and abs(errors.mean() - metrics["relative_l2_mean"]) < 1e-12 | |
| with (results / "training_history.csv").open() as stream: | |
| history = list(csv.DictReader(stream)) | |
| assert [int(row["epoch"]) for row in history] == list(range(1, 501)) | |
| training_losses = np.array([float(row["train_squared_relative_l2"]) for row in history]) | |
| assert int(training_losses.argmin()) + 1 == metrics["selected_epoch"] | |
| selected = [0, int(np.argsort(errors)[len(errors) // 2]), int(errors.argmax())] | |
| fig, axes = plt.subplots(3, 4, figsize=(14, 9), constrained_layout=True) | |
| for row, sample_id in enumerate(selected): | |
| permeability = saved["x"][sample_id, 0].numpy() | |
| truth = saved["y"][sample_id, 0].numpy() | |
| prediction = saved["prediction"][sample_id, 0].numpy() | |
| difference = np.abs(prediction - truth) | |
| lower, upper = min(truth.min(), prediction.min()), max(truth.max(), prediction.max()) | |
| for column, (array, title, cmap, vmin, vmax) in enumerate([ | |
| (permeability, "Permeability", "viridis", permeability.min(), permeability.max()), | |
| (truth, "True pressure", "viridis", lower, upper), | |
| (prediction, "Predicted pressure", "viridis", lower, upper), | |
| (difference, "Absolute error", "inferno", 0, difference.max()), | |
| ]): | |
| ax = axes[row, column] | |
| im = ax.imshow(array.T, origin="lower", extent=[0, 1, 0, 1], | |
| interpolation="nearest", cmap=cmap, vmin=vmin, vmax=vmax) | |
| ax.set_title(f"{title}: sample {sample_id}" if column != 3 else | |
| f"{title}: rel L2={errors[sample_id]:.4f}") | |
| ax.set_xlabel("Coordinate 1") | |
| ax.set_ylabel("Coordinate 2") | |
| fig.colorbar(im, ax=ax, shrink=.8, format="%.3g") | |
| fig.suptitle("SirenFNO Darcy 32x32: original-scale fields; fixed, median-error and worst samples") | |
| fig.savefig(results / "darcy_fields.png", dpi=180) | |
| fig.savefig(results / "darcy_fields.pdf") | |
| plt.close(fig) | |
| epochs = np.arange(1, 501) | |
| fig, axes = plt.subplots(1, 2, figsize=(12, 4), constrained_layout=True) | |
| for name, label in [("train_relative_l2", "Train, original scale"), ("test_relative_l2", "Test, original scale")]: | |
| axes[0].semilogy(epochs, [float(row[name]) for row in history], label=label) | |
| axes[0].axhline(.0351, color="black", ls="--", label="Paper Table 2: 0.0351") | |
| axes[0].axvline(metrics["selected_epoch"], color="grey", ls=":", label="Training-selected checkpoint") | |
| axes[0].set(xlabel="Epoch", ylabel="Mean per-sample relative L2") | |
| axes[0].legend(fontsize=8) | |
| axes[1].semilogy(epochs, training_losses, label="Full training set, paper Eq15") | |
| axes[1].semilogy(epochs, [float(row["test_squared_relative_l2"]) for row in history], label="Test, squared relative L2") | |
| axes[1].set(xlabel="Epoch", ylabel="Mean squared per-sample relative L2") | |
| axes[1].legend(fontsize=8) | |
| fig.savefig(results / "training_curves.png", dpi=180) | |
| plt.close(fig) | |
| fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True) | |
| ax.hist(errors, bins=25, color="#317a9b", edgecolor="white") | |
| ax.axvline(errors.mean(), color="#c45b35", label=f"Run mean {errors.mean():.6f}") | |
| ax.axvline(.0351, color="black", ls="--", label="Paper Table 2: 0.0351") | |
| ax.set(xlabel="Per-sample relative L2, original scale", ylabel="Test samples") | |
| ax.legend() | |
| fig.savefig(results / "error_distribution.png", dpi=180) | |
| plt.close(fig) | |
| metadata = json.loads((results / "run_metadata.json").read_text()) | |
| status = json.loads((results / "training_status.json").read_text()) | |
| text = f"""# SirenFNO Table 2 / Darcy 32×32 复现结果 | |
| 正式训练已完成 **{metrics['completed_epochs']} epoch**,batch size 32,训练 1000 个、测试 200 个样本。 | |
| 加载 `weight/best_model.pth` 后,原尺度逐样本相对 L2 算术均值为 **{metrics['relative_l2_mean']:.10f}**。 | |
| 对比论文 Table 2 的 **0.0351**:有符号差距 **{metrics['signed_gap']:+.10f}**,绝对差距 **{metrics['absolute_gap']:.10f}**,相对差距 **{metrics['relative_gap_percent']:+.3f}%**。 | |
| ## 指标与权重 | |
| - 主指标:对每个样本计算 `||prediction-y||_2 / ||y||_2`,对 200 个样本取算术均值;由保存的原尺度 float32 场使用 float64 重新计算。 | |
| - 论文式 (15) 字面上的平方相对 L2 均值:**{metrics['squared_relative_l2_mean']:.10f}**。它与主指标不是同一统计量。 | |
| - 最优权重选择:每个 epoch 后在完整训练集上以 eval 模式计算原尺度平方相对 L2,取最小者;选中 **epoch {metrics['selected_epoch']}**。 | |
| - 测试集每轮用于监测,**不用于选权重、调参或早停**;无独立验证集。论文没有说明权重选择规则,本规则属于显式工程假设。 | |
| - 末轮 epoch 500 的原尺度测试相对 L2:**{metrics['last_epoch_test_relative_l2']:.10f}**;末轮权重保存在 `weight/last_model.pth`。 | |
| - checkpoint SHA256:`{metrics['checkpoint_sha256']}`。 | |
| - 实际本轮训练墙钟时间:{status['wall_seconds']:.2f} 秒;参数量:{metadata['parameters']}。 | |
| ## 对齐情况与限制 | |
| 1. 本次是非分解完整 SirenFNO,四层 32 通道,式 (14) 的增强残差结构,全部 32×17 个独立 rFFT 频点生成稠密 32×32 复系数;没有任何频率截断。rFFT 半谱是实数输入的厄米冗余压缩,不是高频截断。 | |
| 2. 论文 §5.2 的 AdamW、lr=1e-3、weight decay=1e-4、CosineAnnealingLR(T_max=500)、500 epoch、batch=32 均执行。无提前停止、无降采样、无额外训练数据。预先冒烟训练的模型已丢弃,正式训练从 seed 42 重新初始化。 | |
| 3. 论文式 (7) 明确写 sin,本次使用纯 sin 及可学习偏置;官方仓库使用交错 sin/cos 且无偏置,本次没有用该冲突实现覆盖论文。 | |
| 4. 论文 §5.2 指定 lifting/projection 隐藏宽度 64,本次使用 3→64→32 和 32→64→1。仓库使用单层 3→32 lifting 和 32→128→1 projection;因此本次参数量不要求等于 Table 3 的约 308.9k。 | |
| 5. 论文式 (15) 在 PDF 上是范数平方之比,但文字称相对 L2、仓库 LpLoss 使用未平方比值。本次训练在原尺度使用平方比值以遵循字面公式,报告同时给出用户指定的未平方指标。**无法断言 Table 2 的 0.0351 究竟对应公式还是仓库口径,因此数值差距只是指定口径下的直接比较,不代表已精确匹配作者训练实现。** | |
| 6. 论文未给出的 RFF 特征数 16、sigma=512、SIREN 隐藏宽度 32/一层、omega 初值、midpoint 频率索引、残差 MLP 扩张 4、坐标拼接、无 padding、seed 42、无 shuffle,以及训练集压力 channel-wise 标准化,来自官方仓库只读参考。输入渗透率保持原值;压力标准化统计量仅来自 1000 个训练样本,模型输出先反归一化再计算训练 loss 和评测指标。 | |
| 7. 运行设备为 **{metadata['device']}**,PyTorch **{metadata['torch']}**,HIP **{metadata['hip']}**;论文设备是 RTX 5090。后端和随机数流不同,只有一次固定 seed 运行,没有多种子统计。 | |
| 8. 物理单位及精确边界网格元数据未在 pt 字段中提供,不虚构单位;可视化坐标采用官方输入网格 [0,1] 的约定,不宣称额外 PDE 残差或守恒量验证。 | |
| ## 证据与文件 | |
| - `results/data_manifest.json`:原始 shape/dtype、选样索引、字段语义与数据 SHA256。 | |
| - `results/training_history.csv`:500 轮实际记录,含 train/test 两种误差及学习率。 | |
| - `results/per_sample_metrics.csv`:200 个测试样本原尺度误差。 | |
| - `results/predictions.pt`:原尺度输入、真值、预测、样本索引。 | |
| - `results/darcy_fields.png`、`darcy_fields.pdf`:固定第 0 个、误差中位样本、最差样本,真值与预测使用同一色标。 | |
| - `results/training_curves.png`、`error_distribution.png`:训练曲线及误差分布。 | |
| - `results/smoke/checks.json`:六项计算节点冒烟检查。 | |
| - `reproduction_spec.md`:完整来源、缺口与冲突决策;`logs/`:Slurm 实时 print 日志。 | |
| 论文:[IJCAI PDF](https://ijcai.org/proceedings/2026/0535.pdf)。补充细节:[官方仓库只读参考](https://github.com/pengqingshi/SirenFNO)。未下载、克隆或复制官方仓库代码,所有实现均独立编写;未提交 Git、未上传平台。 | |
| """ | |
| (results / "report.md").write_text(text) | |
| atomic_json(results / "verification.json", {"status": "passed", "completed_epochs": 500, | |
| "history_rows": 500, "test_samples": 200, "original_scale_metric_recomputed": True, | |
| "checkpoint_selection_verified": True, "figure_sample_ids": selected, | |
| "figures": ["darcy_fields.png", "darcy_fields.pdf", "training_curves.png", "error_distribution.png"]}) | |
| print(f"RESULTS VERIFIED: {results / 'report.md'}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |