pth2onnx.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import torch
  2. import onnx
  3. import torch.onnx
  4. import onnxruntime as ort
  5. import numpy as np
  6. from torchvision.models import resnet50, shufflenet_v2_x1_0, shufflenet_v2_x2_0
  7. from torch import nn
  8. # from simple_model import SimpleModel
  9. if __name__ == '__main__':
  10. # 载入模型框架
  11. # model = SimpleModel()
  12. model = resnet50(pretrained=False)
  13. # model = shufflenet_v2_x1_0()
  14. model_name = "resnet50"
  15. model.fc = nn.Linear(int(model.fc.in_features), 2, bias=True)
  16. model.load_state_dict(torch.load(rf'./{model_name}.pth')) # xxx.pth表示.pth文件, 这一步载入模型权重
  17. print("加载模型成功")
  18. model.eval() # 设置模型为推理模式
  19. example_input = torch.randn(1, 3, 256, 256) # [1,3,224,224]分别对应[B,C,H,W]
  20. # print(model)
  21. torch.onnx.export(model,
  22. example_input,
  23. f"{model_name}.onnx",
  24. opset_version=13,
  25. export_params=True,
  26. do_constant_folding=True,
  27. ) # xxx.onnx表示.onnx文件, 这一步导出为onnx模型, 并不做任何算子融合操作。
  28. # 验证模型
  29. onnx_model = onnx.load(f"{model_name}.onnx") # 使用不同变量名
  30. onnx.checker.check_model(onnx_model) # 验证模型完整性
  31. # 使用ONNX Runtime进行推理
  32. ort_session = ort.InferenceSession(f"{model_name}.onnx")
  33. ort_inputs = {ort_session.get_inputs()[0].name: example_input.detach().numpy()}
  34. ort_outs = ort_session.run(None, ort_inputs)
  35. # 与PyTorch原始输出对比
  36. with torch.no_grad():
  37. torch_out = model(example_input)
  38. # 检查最大误差
  39. print("输出差异最大为:", np.max(np.abs(torch_out.numpy() - ort_outs[0])))
  40. #mean_mlir = [0.485×255, 0.456×255, 0.406×255] = [123.675, 116.28, 103.53]
  41. #scale_mlir = [0.229*255, 0.224*255, 0.225*255] = [58.395, 57.12, 57.375]