{
  "source_file": "0930",
  "source_platform": "研究机构",
  "author": "PyTorch Tutorials",
  "title_listed": "Exporting a PyTorch model to ONNX",
  "keywords": "ONNX,部署,推理",
  "domain": "机器学习",
  "content_type": "教程",
  "is_paid_flag": "否",
  "url": "https://pytorch.org/tutorials/beginner/onnx/export_simple_model_to_onnx_tutorial.html",
  "publish_date": "持续更新",
  "corpus_stage": "机器学习",
  "notes": "模型导出 ONNX",
  "id": "e55b1827bac1",
  "collected_at": "2026-10-02T16:58:34",
  "title": "Export a PyTorch model to ONNX — PyTorch Tutorials 2.14.0+cu130 documentation",
  "body_markdown": "Note\nGo to the end\nto download the full example code.\nIntroduction to ONNX\n||\nExporting a PyTorch model to ONNX\n||\nExtending the ONNX exporter operator support\n||\nExport a model with control flow to ONNX\nExport a PyTorch model to ONNX\n#\nCreated On: Oct 04, 2023 | Last Updated: Jul 11, 2025 | Last Verified: Nov 05, 2024\nAuthor\n:\nTi-Tai Wang\n,\nJustin Chu\n,\nThiago Crepaldi\n.\nNote\nStarting with PyTorch 2.5, there are two ONNX Exporter options available.\n*\ntorch.onnx.export(...,\ndynamo=True)\nis the recommended exporter that leverages\ntorch.export\nand Torch FX for graph capture.\n*\ntorch.onnx.export\nis the legacy approach that relies on the deprecated TorchScript and is no longer recommended for use.\nIn the\n60 Minute Blitz\n,\nwe had the opportunity to learn about PyTorch at a high level and train a small neural network to classify images.\nIn this tutorial, we are going to expand this to describe how to convert a model defined in PyTorch into the\nONNX format using the\ntorch.onnx.export(...,\ndynamo=True)\nONNX exporter.\nWhile PyTorch is great for iterating on the development of models, the model can be deployed to production\nusing different formats, including\nONNX\n(Open Neural Network Exchange)!\nONNX is a flexible open standard format for representing machine learning models which standardized representations\nof machine learning allow them to be executed across a gamut of hardware platforms and runtime environments\nfrom large-scale cloud-based supercomputers to resource-constrained edge devices, such as your web browser and phone.\nIn this tutorial, we’ll learn how to:\nInstall the required dependencies.\nAuthor a simple image classifier model.\nExport the model to ONNX format.\nSave the ONNX model in a file.\nVisualize the ONNX model graph using\nNetron\n.\nExecute the ONNX model with\nONNX Runtime\nCompare the PyTorch results with the ones from the ONNX Runtime.\n1. Install the required dependencies\n#\nBecause the ONNX exporter uses\nonnx\nand\nonnxscript\nto translate PyTorch operators into ONNX operators,\nwe will need to install them.\npip\ninstall\n--upgrade\nonnx\nonnxscript\n2. Author a simple image classifier model\n#\nOnce your environment is set up, let’s start modeling our image classifier with PyTorch,\nexactly like we did in the\n60 Minute Blitz\n.\nimport\ntorch\nimport\ntorch.nn\nas\nnn\nimport\ntorch.nn.functional\nas\nF\nclass\nImageClassifierModel\n(\nnn\n.\nModule\n):\ndef\n__init__\n(\nself\n):\nsuper\n()\n.\n__init__\n()\nself\n.\nconv1\n=\nnn\n.\nConv2d\n(\n1\n,\n6\n,\n5\n)\nself\n.\nconv2\n=\nnn\n.\nConv2d\n(\n6\n,\n16\n,\n5\n)\nself\n.\nfc1\n=\nnn\n.\nLinear\n(\n16\n*\n5\n*\n5\n,\n120\n)\nself\n.\nfc2\n=\nnn\n.\nLinear\n(\n120\n,\n84\n)\nself\n.\nfc3\n=\nnn\n.\nLinear\n(\n84\n,\n10\n)\ndef\nforward\n(\nself\n,\nx\n:\ntorch\n.\nTensor\n):\nx\n=\nF\n.\nmax_pool2d\n(\nF\n.\nrelu\n(\nself\n.\nconv1\n(\nx\n)),\n(\n2\n,\n2\n))\nx\n=\nF\n.\nmax_pool2d\n(\nF\n.\nrelu\n(\nself\n.\nconv2\n(\nx\n)),\n2\n)\nx\n=\ntorch\n.\nflatten\n(\nx\n,\n1\n)\nx\n=\nF\n.\nrelu\n(\nself\n.\nfc1\n(\nx\n))\nx\n=\nF\n.\nrelu\n(\nself\n.\nfc2\n(\nx\n))\nx\n=\nself\n.\nfc3\n(\nx\n)\nreturn\nx\n3. Export the model to ONNX format\n#\nNow that we have our model defined, we need to instantiate it and create a random 32x32 input.\nNext, we can export the model to ONNX format.\ntorch_model\n=\nImageClassifierModel\n()\n# Create example inputs for exporting the model. The inputs should be a tuple of tensors.\nexample_inputs\n=\n(\ntorch\n.\nrandn\n(\n1\n,\n1\n,\n32\n,\n32\n),)\nonnx_program\n=\ntorch\n.\nonnx\n.\nexport\n(\ntorch_model\n,\nexample_inputs\n,\ndynamo\n=\nTrue\n)\n/var/lib/workspace/beginner_source/onnx/export_simple_model_to_onnx_tutorial.py:93: UserWarning: Exporting a model while it is in training mode. Please ensure that this is intended, as it may lead to different behavior during inference. Calling model.eval() before export is recommended.\n  onnx_program = torch.onnx.export(torch_model, example_inputs, dynamo=True)\n[torch.onnx] Obtain model graph for `ImageClassifierModel([...]` with `torch.export.export(..., strict=False)`...\n[torch.onnx] Obtain model graph for `ImageClassifierModel([...]` with `torch.export.export(..., strict=False)`... ✅\n[torch.onnx] Run decompositions...\n[torch.onnx] Run decompositions... ✅\n[torch.onnx] Translate the graph into ONNX...\n[torch.onnx] Translate the graph into ONNX... ✅\n[torch.onnx] Optimize the ONNX graph...\n[torch.onnx] Optimize the ONNX graph... ✅\nAs we can see, we didn’t need any code change to the model.\nThe resulting ONNX model is stored within\ntorch.onnx.ONNXProgram\nas a binary protobuf file.\n4. Save the ONNX model in a file\n#\nAlthough having the exported model loaded in memory is useful in many applications,\nwe can save it to disk with the following code:\nonnx_program\n.\nsave\n(\n\"image_classifier_model.onnx\"\n)\nYou can load the ONNX file back into memory and check if it is well formed with the following code:\nimport\nonnx\nonnx_model\n=\nonnx\n.\nload\n(\n\"image_classifier_model.onnx\"\n)\nonnx\n.\nchecker\n.\ncheck_model\n(\nonnx_model\n)\n5. Visualize the ONNX model graph using Netron\n#\nNow that we have our model saved in a file, we can visualize it with\nNetron\n.\nNetron can either be installed on macos, Linux or Windows computers, or run directly from the browser.\nLet’s try the web version by opening the following link:\nhttps://netron.app/\n.\nOnce Netron is open, we can drag and drop our\nimage_classifier_model.onnx\nfile into the browser or select it after\nclicking the\nOpen model\nbutton.\nAnd that is it! We have successfully exported our PyTorch model to ONNX format and visualized it with Netron.\n6. Execute the ONNX model with ONNX Runtime\n#\nThe last step is executing the ONNX model with\nONNX Runtime\n, but before we do that, let’s install ONNX Runtime.\npip\ninstall\nonnxruntime\nThe ONNX standard does not support all the data structure and types that PyTorch does,\nso we need to adapt PyTorch input’s to ONNX format before feeding it to ONNX Runtime.\nIn our example, the input happens to be the same, but it might have more inputs\nthan the original PyTorch model in more complex models.\nONNX Runtime requires an additional step that involves converting all PyTorch tensors to Numpy (in CPU)\nand wrap them on a dictionary with keys being a string with the input name as key and the numpy tensor as the value.\nNow we can create an\nONNX Runtime Inference Session\n, execute the ONNX model with the processed input\nand get the output. In this tutorial, ONNX Runtime is executed on CPU, but it could be executed on GPU as well.\nimport\nonnxruntime\nonnx_inputs\n=\n[\ntensor\n.\nnumpy\n(\nforce\n=\nTrue\n)\nfor\ntensor\nin\nexample_inputs\n]\nprint\n(\nf\n\"Input length:\n{\nlen\n(\nonnx_inputs\n)\n}\n\"\n)\nprint\n(\nf\n\"Sample input:\n{\nonnx_inputs\n}\n\"\n)\nort_session\n=\nonnxruntime\n.\nInferenceSession\n(\n\"./image_classifier_model.onnx\"\n,\nproviders\n=\n[\n\"CPUExecutionProvider\"\n]\n)\nonnxruntime_input\n=\n{\ninput_arg\n.\nname\n:\ninput_value\nfor\ninput_arg\n,\ninput_value\nin\nzip\n(\nort_session\n.\nget_inputs\n(),\nonnx_inputs\n)}\n# ONNX Runtime returns a list of outputs\nonnxruntime_outputs\n=\nort_session\n.\nrun\n(\nNone\n,\nonnxruntime_input\n)[\n0\n]\nInput length: 1\nSample input: [array([[[[-0.20974885,  1.347752  ,  1.0131406 , ..., -0.7394197 ,\n           0.5217968 ,  0.04697618],\n         [ 0.28447378, -0.1500617 ,  2.8471766 , ...,  0.6810472 ,\n          -0.82618576, -0.80147725],\n         [-1.4033982 , -0.5368195 , -1.7944473 , ...,  0.2392889 ,\n          -0.05319693,  1.4385749 ],\n         ...,\n         [ 1.3638097 , -0.5138313 , -0.26229423, ...,  1.1000407 ,\n          -0.5134804 ,  1.4998266 ],\n         [ 0.26539308,  1.7628617 , -0.434441  , ..., -0.4689448 ,\n          -1.7610056 ,  0.39201292],\n         [-1.3358176 ,  0.9913115 , -1.275333  , ...,  0.05408644,\n          -0.9840145 ,  0.29884794]]]], dtype=float32)]\n7. Compare the PyTorch results with the ones from the ONNX Runtime\n#\nThe best way to determine whether the exported model is looking good is through numerical evaluation\nagainst PyTorch, which is our source of truth.\nFor that, we need to execute the PyTorch model with the same input and compare the results with ONNX Runtime’s.\nBefore comparing the results, we need to convert the PyTorch’s output to match ONNX’s format.\ntorch_outputs\n=\ntorch_model\n(\n*\nexample_inputs\n)\nassert\nlen\n(\ntorch_outputs\n)\n==\nlen\n(\nonnxruntime_outputs\n)\nfor\ntorch_output\n,\nonnxruntime_output\nin\nzip\n(\ntorch_outputs\n,\nonnxruntime_outputs\n):\ntorch\n.\ntesting\n.\nassert_close\n(\ntorch_output\n,\ntorch\n.\ntensor\n(\nonnxruntime_output\n))\nprint\n(\n\"PyTorch and ONNX Runtime output matched!\"\n)\nprint\n(\nf\n\"Output length:\n{\nlen\n(\nonnxruntime_outputs\n)\n}\n\"\n)\nprint\n(\nf\n\"Sample output:\n{\nonnxruntime_outputs\n}\n\"\n)\nPyTorch and ONNX Runtime output matched!\nOutput length: 1\nSample output: [[ 0.00746908  0.01399638  0.0281431   0.07448272  0.0609627  -0.01600733\n   0.06285256 -0.06786973 -0.05649524 -0.00350285]]\nConclusion\n#\nThat is about it! We have successfully exported our PyTorch model to ONNX format,\nsaved the model to disk, viewed it using Netron, executed it with ONNX Runtime\nand finally compared its numerical results with PyTorch’s.\nFurther reading\n#\nThe list below refers to tutorials that ranges from basic examples to advanced scenarios,\nnot necessarily in the order they are listed.\nFeel free to jump directly to specific topics of your interest or\nsit tight and have fun going through all of them to learn all there is about the ONNX exporter.\n1.\nExporting a PyTorch model to ONNX\n2.\nExtending the ONNX exporter operator support\n3.\nExport a model with control flow to ONNX\nTotal running time of the script:\n(0 minutes 1.902 seconds)\nDownload\nJupyter\nnotebook:\nexport_simple_model_to_onnx_tutorial.ipynb\nDownload\nPython\nsource\ncode:\nexport_simple_model_to_onnx_tutorial.py\nDownload\nzipped:\nexport_simple_model_to_onnx_tutorial.zip",
  "metadata": {
    "title": "Export a PyTorch model to ONNX — PyTorch Tutorials 2.14.0+cu130 documentation",
    "description": null,
    "keywords": null,
    "author": null,
    "og:image": "https://docs.pytorch.org/docs/stable/_static/img/pytorch_seo.png",
    "article:modified_time": "2025-03-05T23:36:14+00:00"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "file": "attachments/e55b1827bac1/code/body-000.txt",
      "chars": 38,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-001.txt",
      "chars": 646,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-002.txt",
      "chars": 248,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-003.txt",
      "chars": 843,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-004.txt",
      "chars": 49,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-005.txt",
      "chars": 104,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-006.txt",
      "chars": 24,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-007.txt",
      "chars": 522,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-008.txt",
      "chars": 688,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-009.txt",
      "chars": 410,
      "language": "text"
    },
    {
      "file": "attachments/e55b1827bac1/code/body-010.txt",
      "chars": 199,
      "language": "text"
    }
  ],
  "images": [
    {
      "status": "ok",
      "url": "https://docs.pytorch.org/tutorials/_images/netron_web_ui.png",
      "bytes": 66098,
      "reused": false,
      "local_path": "attachments/e55b1827bac1/images/body-bd5a1f155a50d0a97dbe.png",
      "src": "https://docs.pytorch.org/tutorials/_images/netron_web_ui.png",
      "alt": "../../_images/netron_web_ui.png",
      "downloaded": true
    },
    {
      "status": "ok",
      "url": "https://docs.pytorch.org/tutorials/_images/image_classifier_onnx_model_on_netron_web_ui.png",
      "bytes": 61983,
      "reused": false,
      "local_path": "attachments/e55b1827bac1/images/body-cde664c70e6044cd9030.png",
      "src": "https://docs.pytorch.org/tutorials/_images/image_classifier_onnx_model_on_netron_web_ui.png",
      "alt": "../../_images/image_classifier_onnx_model_on_netron_web_ui.png",
      "downloaded": true
    }
  ],
  "audio": [],
  "videos": [],
  "links": [
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/onnx/intro_onnx.html",
      "label": "Introduction to ONNX",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/onnx/onnx_registry_tutorial.html",
      "label": "Extending the ONNX exporter operator support",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/onnx/export_control_flow_model_to_onnx_tutorial.html",
      "label": "Export a model with control flow to ONNX",
      "type": "a"
    },
    {
      "href": "https://github.com/titaiwangms",
      "label": "Ti-Tai Wang",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/cdn-cgi/l/email-protection",
      "label": "Justin Chu",
      "type": "a"
    },
    {
      "href": "https://github.com/thiagocrepaldi",
      "label": "Thiago Crepaldi",
      "type": "a"
    },
    {
      "href": "https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html",
      "label": "60 Minute Blitz",
      "type": "a"
    },
    {
      "href": "https://onnx.ai/",
      "label": "ONNX",
      "type": "a"
    },
    {
      "href": "https://github.com/lutzroeder/netron",
      "label": "Netron",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html",
      "label": "nn . Module",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.nn.Conv2d.html",
      "label": "nn . Conv2d",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.nn.Linear.html",
      "label": "nn . Linear",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/tensors.html",
      "label": "torch . Tensor",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.max_pool2d.html",
      "label": "F . max_pool2d",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.nn.functional.relu.html",
      "label": "F . relu",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.flatten.html",
      "label": "torch . flatten",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.randn.html",
      "label": "torch . randn",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/onnx_export.html",
      "label": "onnx_program",
      "type": "a"
    },
    {
      "href": "https://netron.app/",
      "label": "https://netron.app/",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/_images/netron_web_ui.png",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/_images/image_classifier_onnx_model_on_netron_web_ui.png",
      "label": "",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/testing.html",
      "label": "torch . testing . assert_close",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/docs/stable/generated/torch.tensor.html",
      "label": "torch . tensor",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/beginner/onnx/export_simple_model_to_onnx_tutorial.html",
      "label": "Exporting a PyTorch model to ONNX",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/_downloads/8dd55b9d6d32d45fae2642c7ffbf454e/export_simple_model_to_onnx_tutorial.ipynb",
      "label": "Download Jupyter notebook: export_simple_model_to_onnx_tutorial.ipynb",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/_downloads/1c960eb430ba8694b1655bb03904dac2/export_simple_model_to_onnx_tutorial.py",
      "label": "Download Python source code: export_simple_model_to_onnx_tutorial.py",
      "type": "a"
    },
    {
      "href": "https://docs.pytorch.org/tutorials/_downloads/c385f7abbf301b718185244a648eca3e/export_simple_model_to_onnx_tutorial.zip",
      "label": "Download zipped: export_simple_model_to_onnx_tutorial.zip",
      "type": "a"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-14T10:54:03Z",
  "source_url": "https://pytorch.org/tutorials/beginner/onnx/export_simple_model_to_onnx_tutorial.html",
  "papers": [],
  "actual_video_files": [],
  "body_chars": 9547,
  "expected_body_images": 2,
  "discovery_status": "ok",
  "delivery_status": "ok",
  "missing_reason": "",
  "raw_html": "attachments/e55b1827bac1/pages/source.html",
  "local_html": "attachments/e55b1827bac1/pages/article.html",
  "body_base_path": "attachments/e55b1827bac1/pages/",
  "body_markdown_path": "attachments/e55b1827bac1/pages/article.md"
}