{ "cells": [ { "cell_type": "markdown", "id": "da6e9cca-6893-4273-a558-3dc18d49615e", "metadata": {}, "source": [ "# Getting started with ONNX IR 🌱\n", "The ONNX IR is available as `onnx_ir`. Use `ir.load(\"model.onnx\")` to load\n", "a model from disk. This notebook starts from ONNX text so it is self-contained,\n", "then demonstrates inspection, transformation, validation, and saving." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# Define an example model for this example\n", "MODEL_TEXT = r\"\"\"\n", "<\n", " ir_version: 8,\n", " opset_import: [\"\" : 18],\n", " producer_name: \"pytorch\",\n", " producer_version: \"2.0.0\"\n", ">\n", "torch_jit (float[5,5,5] input_0) => (float[5,5] val_19, float[5,5] val_6) {\n", " [node_1] val_1 = Constant ()\n", " [node_2] val_2 = Shape (val_1)\n", " [node_3] val_3 = Size (val_2)\n", " [node_4] val_4 = Constant ()\n", " [node_5] val_5 = Equal (val_3, val_4)\n", " [node_6] val_6 = ReduceMean (input_0, val_1)\n", " [node_7] val_7 = ReduceMean (input_0, val_1)\n", " [node_8] val_8 = Shape (input_0)\n", " [node_9] val_9 = Gather (val_8, val_1)\n", " [node_10] val_10 = ReduceProd (val_9)\n", " [node_11] val_11 = Sub (input_0, val_7)\n", " [node_12] val_12 = Mul (val_11, val_11)\n", " [node_13] val_13 = ReduceMean (val_12, val_1)\n", " [node_14] val_14 = Cast (val_10)\n", " [node_15] val_15 = Mul (val_13, val_14)\n", " [node_16] val_16 = Constant ()\n", " [node_17] val_17 = Sub (val_10, val_16)\n", " [node_18] val_18 = Cast (val_17)\n", " [node_19] val_19 = Div (val_15, val_18)\n", "}\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 2, "id": "cb5e7520-1aba-491b-b3e9-7d013e42d4ff", "metadata": {}, "outputs": [], "source": [ "import onnx\n", "\n", "import onnx_ir as ir\n", "\n", "# Load the model as onnx.ModelProto\n", "# You can also load the model from a file using onnx.load(\"model.onnx\")\n", "model_proto = onnx.parser.parse_model(MODEL_TEXT)\n", "\n", "# Create an IR object from the model\n", "model = ir.from_proto(model_proto)" ] }, { "cell_type": "markdown", "id": "8f02f283-93c3-4e8f-b8f4-275f360ace61", "metadata": {}, "source": [ "Now we can explore the IR object" ] }, { "cell_type": "code", "execution_count": 3, "id": "969233d0-5e7a-4554-b4bc-ea06f448dd98", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The main graph has 19 nodes.\n" ] } ], "source": [ "print(f\"The main graph has {len(model.graph)} nodes.\")" ] }, { "cell_type": "markdown", "id": "0422514a-72d3-40a0-9734-c58911ddefc9", "metadata": {}, "source": [ "All inputs" ] }, { "cell_type": "code", "execution_count": 4, "id": "7b5689d8-dd2e-468f-9a87-653e97be7cf9", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Value(name='input_0', type=Tensor(FLOAT), shape=Shape([5, 5, 5]))]\n" ] } ], "source": [ "print(model.graph.inputs)" ] }, { "cell_type": "markdown", "id": "d299db39-08f9-4646-856d-74e9cb18ee8a", "metadata": {}, "source": [ "All outputs" ] }, { "cell_type": "code", "execution_count": 5, "id": "e3fb01aa-2ca5-4839-80c4-2c2d1b916a1c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Value(name='val_19', type=Tensor(FLOAT), shape=Shape([5, 5]), producer='node_19', index=0), Value(name='val_6', type=Tensor(FLOAT), shape=Shape([5, 5]), producer='node_6', index=0)]\n" ] } ], "source": [ "print(model.graph.outputs)" ] }, { "cell_type": "markdown", "id": "1c52c8a2-52b4-40f3-996a-d44488e62623", "metadata": {}, "source": [ "Nodes that uses the first input" ] }, { "cell_type": "code", "execution_count": 6, "id": "c4894e97-7a8f-4f61-86dd-dd44aced02ed", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[Usage(node=Node(name='node_6', domain='', op_type='ReduceMean', inputs=(Value(name='input_0', type=Tensor(FLOAT), shape=Shape([5, 5, 5])), Value(name='val_1', producer='node_1', index=0)), attributes={'keepdims': Attr('keepdims', INT, 0), 'noop_with_empty_axes': Attr('noop_with_empty_axes', INT, 0)}, overload='', outputs=(Value(name='val_6', type=Tensor(FLOAT), shape=Shape([5, 5]), producer='node_6', index=0),), version=None, doc_string=None), idx=0), Usage(node=Node(name='node_7', domain='', op_type='ReduceMean', inputs=(Value(name='input_0', type=Tensor(FLOAT), shape=Shape([5, 5, 5])), Value(name='val_1', producer='node_1', index=0)), attributes={'keepdims': Attr('keepdims', INT, 1), 'noop_with_empty_axes': Attr('noop_with_empty_axes', INT, 0)}, overload='', outputs=(Value(name='val_7', producer='node_7', index=0),), version=None, doc_string=None), idx=0), Usage(node=Node(name='node_8', domain='', op_type='Shape', inputs=(Value(name='input_0', type=Tensor(FLOAT), shape=Shape([5, 5, 5])),), attributes={'start': Attr('start', INT, 0)}, overload='', outputs=(Value(name='val_8', producer='node_8', index=0),), version=None, doc_string=None), idx=0), Usage(node=Node(name='node_11', domain='', op_type='Sub', inputs=(Value(name='input_0', type=Tensor(FLOAT), shape=Shape([5, 5, 5])), Value(name='val_7', producer='node_7', index=0)), attributes={}, overload='', outputs=(Value(name='val_11', producer='node_11', index=0),), version=None, doc_string=None), idx=0)]\n" ] } ], "source": [ "print(list(model.graph.inputs[0].uses()))" ] }, { "cell_type": "markdown", "id": "36d935b0-1910-4e7b-a2d8-57f6fa129670", "metadata": {}, "source": [ "The node that produces the last output (as the i-th output)" ] }, { "cell_type": "code", "execution_count": 7, "id": "ac16cc49-9c82-4d5e-9c77-f0fd6260929b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "%\"val_6\" ⬅️ ::ReduceMean(%\"input_0\", %\"val_1\") {keepdims=0, noop_with_empty_axes=0}\n", "0\n" ] } ], "source": [ "print(model.graph.outputs[-1].producer())\n", "print(model.graph.outputs[-1].index())" ] }, { "cell_type": "markdown", "id": "d70a097f-da71-4299-bbc4-63ad3cc7be67", "metadata": {}, "source": [ "Print the graph" ] }, { "cell_type": "code", "execution_count": 8, "id": "772e831d-8d9d-4446-81ed-e119e8f2c0d6", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "graph(\n", " name=torch_jit,\n", " inputs=(\n", " %\"input_0\"\n", " ),\n", " outputs=(\n", " %\"val_19\",\n", " %\"val_6\"\n", " ),\n", ") {\n", " 0 | # node_1\n", " %\"val_1\" ⬅️ ::Constant() {value_int=(1,)}\n", " 1 | # node_2\n", " %\"val_2\" ⬅️ ::Shape(%\"val_1\") {start=0}\n", " 2 | # node_3\n", " %\"val_3\" ⬅️ ::Size(%\"val_2\")\n", " 3 | # node_4\n", " %\"val_4\" ⬅️ ::Constant() {value=TensorProtoTensor(array(0), name='')}\n", " 4 | # node_5\n", " %\"val_5\" ⬅️ ::Equal(%\"val_3\", %\"val_4\")\n", " 5 | # node_6\n", " %\"val_6\" ⬅️ ::ReduceMean(%\"input_0\", %\"val_1\") {keepdims=0, noop_with_empty_axes=0}\n", " 6 | # node_7\n", " %\"val_7\" ⬅️ ::ReduceMean(%\"input_0\", %\"val_1\") {keepdims=1, noop_with_empty_axes=0}\n", " 7 | # node_8\n", " %\"val_8\" ⬅️ ::Shape(%\"input_0\") {start=0}\n", " 8 | # node_9\n", " %\"val_9\" ⬅️ ::Gather(%\"val_8\", %\"val_1\") {axis=0}\n", " 9 | # node_10\n", " %\"val_10\" ⬅️ ::ReduceProd(%\"val_9\") {keepdims=0, noop_with_empty_axes=0}\n", " 10 | # node_11\n", " %\"val_11\" ⬅️ ::Sub(%\"input_0\", %\"val_7\")\n", " 11 | # node_12\n", " %\"val_12\" ⬅️ ::Mul(%\"val_11\", %\"val_11\")\n", " 12 | # node_13\n", " %\"val_13\" ⬅️ ::ReduceMean(%\"val_12\", %\"val_1\") {keepdims=0, noop_with_empty_axes=0}\n", " 13 | # node_14\n", " %\"val_14\" ⬅️ ::Cast(%\"val_10\") {to=1}\n", " 14 | # node_15\n", " %\"val_15\" ⬅️ ::Mul(%\"val_13\", %\"val_14\")\n", " 15 | # node_16\n", " %\"val_16\" ⬅️ ::Constant() {value=TensorProtoTensor(array(1), name='')}\n", " 16 | # node_17\n", " %\"val_17\" ⬅️ ::Sub(%\"val_10\", %\"val_16\")\n", " 17 | # node_18\n", " %\"val_18\" ⬅️ ::Cast(%\"val_17\") {to=1}\n", " 18 | # node_19\n", " %\"val_19\" ⬅️ ::Div(%\"val_15\", %\"val_18\")\n", " return %\"val_19\", %\"val_6\"\n", "}\n" ] } ], "source": [ "print(model.graph)" ] }, { "cell_type": "markdown", "id": "cf19aa88-2063-4fee-9dd8-5fdca1dab398", "metadata": {}, "source": [ "## Transform the graph\n", "\n", "Add an `Identity` after the second graph output and make its result the new output." ] }, { "cell_type": "code", "execution_count": null, "id": "3b146b60-602a-4cb1-a5f8-d8d22c2a6a72", "metadata": {}, "outputs": [], "source": [ "old_output = model.graph.outputs[-1]\n", "producer = old_output.producer()\n", "assert producer is not None\n", "\n", "identity = ir.node(\"Identity\", inputs=[old_output], name=\"output_identity\")\n", "identity.outputs[0].type = old_output.type\n", "identity.outputs[0].shape = old_output.shape\n", "model.graph.insert_after(producer, identity)\n", "model.graph.outputs[-1] = identity.outputs[0]" ] }, { "cell_type": "markdown", "id": "17d7e6ad-baf9-4bf9-a3c2-279f718ce847", "metadata": {}, "source": [ "The insertion preserves names, ownership, use-def relationships, and topological\n", "order, so no repair passes are needed. At this tutorial's validation boundary,\n", "run the ONNX checker explicitly." ] }, { "cell_type": "code", "execution_count": null, "id": "04a20a22-02d0-42ca-86c4-b02340aa5d1f", "metadata": {}, "outputs": [], "source": [ "import onnx_ir.passes.common as common_passes\n", "\n", "common_passes.CheckerPass(full_check=True)(model)" ] }, { "cell_type": "markdown", "id": "2b0be6bf-3511-46d7-b903-cda2ab246c64", "metadata": {}, "source": [ "## Save and reload\n", "\n", "Use `ir.save` and `ir.load` at file boundaries. A temporary directory keeps this\n", "notebook from leaving generated files behind." ] }, { "cell_type": "code", "execution_count": null, "id": "49a8f598-b119-4694-9e95-94b8a94ad8ad", "metadata": {}, "outputs": [], "source": [ "import os\n", "import tempfile\n", "\n", "with tempfile.TemporaryDirectory() as temp_dir:\n", " model_path = os.path.join(temp_dir, \"model.onnx\")\n", " ir.save(model, model_path)\n", " reloaded_model = ir.load(model_path)\n", "\n", "assert reloaded_model.graph.outputs[-1].producer().op_type == \"Identity\"" ] }, { "cell_type": "markdown", "id": "5be911bc-7e8c-4ba0-a525-52307efc902b", "metadata": {}, "source": [ "Convert to or from `ModelProto` explicitly when integrating with protobuf-based APIs." ] }, { "cell_type": "code", "execution_count": null, "id": "46889035-5d91-494d-a17c-61a6744c91f9", "metadata": {}, "outputs": [], "source": [ "model_proto_back = ir.to_proto(model)\n", "model_round_trip = ir.from_proto(model_proto_back)" ] }, { "cell_type": "markdown", "id": "85a23c5b-81b8-4a73-96e0-c8553712d46f", "metadata": {}, "source": [ "## Next steps\n", "\n", "- Read [Introduction to the IR](ir.md) for design principles and the object model.\n", "- Read [Constructing models](model_construction.md) to build models from scratch.\n", "- Read [Graph transformation patterns](graph_transformations.md) for common rewrites.\n", "- Read [Writing transformation passes](writing_passes.md) for reusable pipelines." ] } ], "metadata": { "kernelspec": { "display_name": "onnx", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.0" } }, "nbformat": 4, "nbformat_minor": 2 }