Files
blackbird/actpred/export_onnx.py
T
qing 3d03f7a1ce actpred: 代码审计(16项发现全部修复)+ 文档更新
审计报告: docs/reviews/actpred_CODE_AUDIT_20260808.md
- P0(2项): episode索引错位(dataset.py)、推理归一化静默失败(predict.py)
- P1(6项): 空训练集校验、图像自然排序、空样本防御、形状校验、
  MobileNet下载错误提示、stats路径校验
- P2(8项): README示例修正、公共属性、glob优化、版本约束、
  单元测试(17项)、GPU安装说明、BooleanOptionalAction、ONNX验证

新增文件: actpred/test_actpred.py (17项单元测试, 全部通过)
更新文档: README.md配置表扩充、INDEX.md、审计报告修复总结
2026-08-08 16:05:01 +00:00

57 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import argparse
import torch
from config import DataConfig, ModelConfig
from model import ActionPredictor
def main():
parser = argparse.ArgumentParser(description="Export actpred model to ONNX")
parser.add_argument("--model", required=True, help="checkpoint path (best_inference.pt)")
parser.add_argument("--output", default="model.onnx", help="output ONNX file path")
args = parser.parse_args()
checkpoint = torch.load(args.model, map_location="cpu", weights_only=True)
cfg_dict = checkpoint["config"]
data_cfg = DataConfig(**cfg_dict["data"])
model_cfg = ModelConfig(**cfg_dict["model"])
model = ActionPredictor(model_cfg, data_cfg)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
dummy_image = torch.randn(1, 3, data_cfg.image_size, data_cfg.image_size)
dummy_history = torch.randn(1, data_cfg.history_len, data_cfg.action_dim)
torch.onnx.export(
model, (dummy_image, dummy_history),
args.output,
input_names=["image", "action_history"],
output_names=["predicted_action"],
dynamic_axes={
"image": {0: "batch"},
"action_history": {0: "batch"},
"predicted_action": {0: "batch"},
},
opset_version=17,
)
print(f"ONNX model exported to: {args.output}")
# 可选:验证导出的 ONNX 模型一致性
try:
import onnxruntime as ort
import numpy as np
sess = ort.InferenceSession(args.output)
img_np = dummy_image.numpy()
hist_np = dummy_history.numpy()
ort_out = sess.run(None, {"image": img_np, "action_history": hist_np})[0]
with torch.no_grad():
torch_out = model(dummy_image, dummy_history).numpy()
max_diff = np.abs(ort_out - torch_out).max()
print(f"ONNX 一致性验证通过(最大差异: {max_diff:.6e})")
except ImportError:
print("提示: 安装 onnxruntime 可验证导出模型一致性 (pip install onnxruntime)")
if __name__ == "__main__":
main()