torch-onnx 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Justin Chu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.1
2
+ Name: torch-onnx
3
+ Version: 0.0.1
4
+ Summary: Experimental tools for converting PyTorch models to ONNX
5
+ Author-email: Justin Chu <justinchu@microsoft.com>
6
+ License: MIT License
7
+ Project-URL: Repository, https://github.com/justinchuby/torch-onnx
8
+ Keywords: onnx,pytorch,converter,convertion,exporter
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: POSIX
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: torch
25
+ Requires-Dist: onnxscript
26
+ Requires-Dist: onnx
27
+
28
+ # PyTorch to ONNX Exporter
29
+
30
+ Experimental torch ONNX exporter.
31
+
32
+ > [!WARNING]
33
+ > This is an experimental project and is not designed for production use.
34
+ > Use `torch.onnx.export` for these purposes.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install torch-onnx
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import torch
46
+ import torch_onnx
47
+ from onnxscript import ir
48
+ import onnx
49
+
50
+ # Get an exported program with torch.export
51
+ exported = torch.export.export(...)
52
+ model = torch_onnx.exported_program_to_ir(exported)
53
+ proto = ir.to_proto(model)
54
+ # This will give you an ATen dialect graph (un-lowered ONNX graph with ATen ops)
55
+ onnx.save(proto, "model.onnx")
56
+ ```
57
+
58
+ ## Design
59
+
60
+ {ExportedProgram, jit} -> {ONNX IR} -> {torchlib} -> {ONNX}
61
+
62
+ - Flat graph; Scope info as metadata, not functions
63
+ - Because existing tools are not good at handling them
64
+ - Eager optimization where appropriate
65
+ - Because exsiting tools are not good at optimizing
66
+ - Drop in replacement for torch.onnx.export
67
+ - Minimum migration effort
68
+ - Use ExportedProgram
69
+ - Rely on robustness of the torch.export implementation
70
+ - This does not solve dynamo limitations, but it avoids introducing additional breakage by running fx passes
71
+ - Build graph eagerly, in place
72
+ - Expose shape and dtype information to the op functions; build with IR
73
+
74
+ ## Why is this doable?
75
+
76
+ - We need to verify torch.export coverage on Huggingface Optimum https://github.com/huggingface/optimum/tree/main/optimum/exporters/onnx; and they are not patching torch.onnx itself.
77
+ - Path torch.onnx.export such that packages do not need to change a single line to use dynamo
78
+ - We have all operators implemented and portable
@@ -0,0 +1,51 @@
1
+ # PyTorch to ONNX Exporter
2
+
3
+ Experimental torch ONNX exporter.
4
+
5
+ > [!WARNING]
6
+ > This is an experimental project and is not designed for production use.
7
+ > Use `torch.onnx.export` for these purposes.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install torch-onnx
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```python
18
+ import torch
19
+ import torch_onnx
20
+ from onnxscript import ir
21
+ import onnx
22
+
23
+ # Get an exported program with torch.export
24
+ exported = torch.export.export(...)
25
+ model = torch_onnx.exported_program_to_ir(exported)
26
+ proto = ir.to_proto(model)
27
+ # This will give you an ATen dialect graph (un-lowered ONNX graph with ATen ops)
28
+ onnx.save(proto, "model.onnx")
29
+ ```
30
+
31
+ ## Design
32
+
33
+ {ExportedProgram, jit} -> {ONNX IR} -> {torchlib} -> {ONNX}
34
+
35
+ - Flat graph; Scope info as metadata, not functions
36
+ - Because existing tools are not good at handling them
37
+ - Eager optimization where appropriate
38
+ - Because exsiting tools are not good at optimizing
39
+ - Drop in replacement for torch.onnx.export
40
+ - Minimum migration effort
41
+ - Use ExportedProgram
42
+ - Rely on robustness of the torch.export implementation
43
+ - This does not solve dynamo limitations, but it avoids introducing additional breakage by running fx passes
44
+ - Build graph eagerly, in place
45
+ - Expose shape and dtype information to the op functions; build with IR
46
+
47
+ ## Why is this doable?
48
+
49
+ - We need to verify torch.export coverage on Huggingface Optimum https://github.com/huggingface/optimum/tree/main/optimum/exporters/onnx; and they are not patching torch.onnx itself.
50
+ - Path torch.onnx.export such that packages do not need to change a single line to use dynamo
51
+ - We have all operators implemented and portable
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "torch-onnx"
7
+ version = "0.0.1"
8
+ description = "Experimental tools for converting PyTorch models to ONNX"
9
+ authors = [{ name = "Justin Chu", email = "justinchu@microsoft.com" }]
10
+ readme = "README.md"
11
+ requires-python = ">=3.8"
12
+ license = {text = "MIT License"}
13
+ keywords = ["onnx", "pytorch", "converter", "convertion", "exporter"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: POSIX",
19
+ "Operating System :: MacOS :: MacOS X",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "License :: OSI Approved :: MIT License",
27
+ ]
28
+ dependencies = ["torch", "onnxscript", "onnx"]
29
+
30
+ [project.urls]
31
+ Repository = "https://github.com/justinchuby/torch-onnx"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,4 @@
1
+ __all__ = ["exported_program_to_ir", "patch_torch"]
2
+
3
+ from ._patch import patch_torch
4
+ from ._core import exported_program_to_ir
@@ -0,0 +1,346 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes
4
+ import inspect
5
+ import itertools
6
+ import logging
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import torch
11
+ import torch.fx
12
+ from onnxscript import ir
13
+ from onnxscript.ir import _convenience as ir_convenience
14
+ from torch.export import graph_signature
15
+
16
+ logger = logging.getLogger(__name__)
17
+ # Define utilities to convert PyTorch data types so users do not need to specify manually
18
+ _TORCH_DTYPE_TO_ONNX: dict[torch.dtype, ir.DataType] = {
19
+ torch.bfloat16: ir.DataType.BFLOAT16,
20
+ torch.bool: ir.DataType.BOOL,
21
+ torch.complex128: ir.DataType.COMPLEX128,
22
+ torch.complex64: ir.DataType.COMPLEX64,
23
+ torch.float16: ir.DataType.FLOAT16,
24
+ torch.float32: ir.DataType.FLOAT,
25
+ torch.float64: ir.DataType.DOUBLE,
26
+ torch.float8_e4m3fn: ir.DataType.FLOAT8E4M3FN,
27
+ torch.float8_e4m3fnuz: ir.DataType.FLOAT8E4M3FNUZ,
28
+ torch.float8_e5m2: ir.DataType.FLOAT8E5M2,
29
+ torch.float8_e5m2fnuz: ir.DataType.FLOAT8E5M2FNUZ,
30
+ torch.int16: ir.DataType.INT16,
31
+ torch.int32: ir.DataType.INT32,
32
+ torch.int64: ir.DataType.INT64,
33
+ torch.int8: ir.DataType.INT8,
34
+ torch.uint8: ir.DataType.UINT8,
35
+ }
36
+
37
+
38
+ def _torch_dtype_to_onnx_dtype(dtype: torch.dtype) -> ir.DataType:
39
+ return _TORCH_DTYPE_TO_ONNX[dtype]
40
+
41
+
42
+ class TorchTensor(ir.Tensor):
43
+ def __init__(self, tensor: torch.Tensor, name: str | None = None):
44
+ # Pass the tensor as the raw data to ir.Tensor's constructor
45
+ super().__init__(
46
+ tensor, dtype=_torch_dtype_to_onnx_dtype(tensor.dtype), name=name
47
+ )
48
+
49
+ def __array__(self, dtype: Any = None) -> np.ndarray:
50
+ # numpy() calls __array__ in ir.Tensor
51
+ if self.dtype == ir.DataType.BFLOAT16:
52
+ return self.raw.view(torch.uint16).__array__(dtype)
53
+ if self.dtype in {
54
+ ir.DataType.FLOAT8E4M3FN,
55
+ ir.DataType.FLOAT8E4M3FNUZ,
56
+ ir.DataType.FLOAT8E5M2,
57
+ ir.DataType.FLOAT8E5M2FNUZ,
58
+ }:
59
+ # TODO: Use ml_dtypes
60
+ return self.raw.view(torch.uint8).__array__(dtype)
61
+ return self.raw.__array__(dtype)
62
+
63
+ def tobytes(self) -> bytes:
64
+ # Implement tobytes to support native PyTorch types so we can use types like bloat16
65
+ # Reading from memory directly is also more efficient because
66
+ # it avoids copying to a NumPy array
67
+ tensor = self.raw.detach().cpu().contiguous()
68
+ return bytes(
69
+ (ctypes.c_ubyte * tensor.element_size() * tensor.numel()).from_address(
70
+ tensor.data_ptr()
71
+ )
72
+ )
73
+
74
+
75
+ # https://github.com/pytorch/pytorch/blob/ee6cb6daa173896f8ea1876266a19775aaa4f610/torch/export/graph_signature.py#L56C1-L62C19
76
+ # class InputKind(Enum):
77
+ # USER_INPUT = auto()
78
+ # PARAMETER = auto()
79
+ # BUFFER = auto()
80
+ # CONSTANT_TENSOR = auto()
81
+ # CUSTOM_OBJ = auto()
82
+ # TOKEN = auto()
83
+
84
+ # https://github.com/pytorch/pytorch/blob/ee6cb6daa173896f8ea1876266a19775aaa4f610/torch/export/graph_signature.py#L89C1-L96C19
85
+ # class OutputKind(Enum):
86
+ # USER_OUTPUT = auto()
87
+ # LOSS_OUTPUT = auto()
88
+ # BUFFER_MUTATION = auto()
89
+ # GRADIENT_TO_PARAMETER = auto()
90
+ # GRADIENT_TO_USER_INPUT = auto()
91
+ # USER_INPUT_MUTATION = auto()
92
+ # TOKEN = auto()
93
+
94
+
95
+ def _set_shape_type(value: ir.Value, meta_val: torch.Tensor | tuple[torch.Tensor]):
96
+ if isinstance(meta_val, tuple):
97
+ logger.warning("Setting shape and type of tensors is not supported yet")
98
+ if isinstance(meta_val, torch.Tensor):
99
+ dims = []
100
+ for dim in meta_val.shape:
101
+ if isinstance(dim, int):
102
+ dims.append(dim)
103
+ else:
104
+ dims.append(str(dim.node))
105
+ value.dtype = _torch_dtype_to_onnx_dtype(meta_val.dtype)
106
+ value.shape = ir.Shape(dims)
107
+ elif isinstance(meta_val, (int, torch.SymInt)):
108
+ # aten::sym_size output is a int, not a tensor, which stands
109
+ # for the size of one dim. We treat it as a scalar.
110
+ value.dtype = ir.DataType.INT64
111
+ value.shape = ir.Shape([])
112
+ elif isinstance(meta_val, (bool, torch.SymBool)):
113
+ value.dtype = ir.DataType.BOOL
114
+ value.shape = ir.Shape([])
115
+ elif isinstance(meta_val, (float, torch.SymFloat)):
116
+ value.dtype = ir.DataType.FLOAT
117
+ value.shape = ir.Shape([])
118
+ else:
119
+ pass
120
+
121
+
122
+ def _get_node_namespace(node: torch.fx.Node) -> tuple[str, str]:
123
+ """Get the namespace and scope of the node.
124
+
125
+ Args:
126
+ node: The node to get the namespace and scope of.
127
+
128
+ Returns:
129
+ A tuple of the namespace and the leave module name.
130
+ """
131
+ nn_module_stack = node.meta.get("nn_module_stack")
132
+ if nn_module_stack is None:
133
+ logging.warning("nn_module_stack not found for node %s", node.name)
134
+ return "", ""
135
+ scopes = []
136
+ module_name = ""
137
+ for name, nn_module in nn_module_stack.values():
138
+ scopes.append(name)
139
+ module_name = repr(nn_module)
140
+
141
+ return "/".join(scopes), module_name
142
+
143
+
144
+ def _set_namespace(node: torch.fx.Node, ir_node: ir.Node):
145
+ nn_module_stack = node.meta.get("nn_module_stack")
146
+ node.meta["nn_module_stack"] = nn_module_stack
147
+ namespace, module_name = _get_node_namespace(node)
148
+ ir_node.metadata_props["namespace"] = namespace
149
+ ir_node.metadata_props["module_name"] = module_name
150
+
151
+
152
+ def _add_nodes(
153
+ exported_program: torch.export.ExportedProgram, graph: ir.Graph
154
+ ) -> dict[str, ir.Value]:
155
+ values: dict[str, ir.Value] = {}
156
+ for node in exported_program.graph.nodes:
157
+ print(node.name, node.args, node.target, node.op, node.type, node.kwargs)
158
+ if node.op == "placeholder":
159
+ # Placeholder nodes are user inputs
160
+ # We need to create a new tensor for each user input
161
+ # and add it to the graph's inputs
162
+ name = node.name
163
+ # shape = node.kwargs["shape"]
164
+ # dtype = node.kwargs["dtype"]
165
+ input_ = ir.Input(name)
166
+ input_.meta["node"] = node
167
+ values[name] = input_
168
+ # The inputs will be added to the graph later
169
+ elif node.op == "call_function":
170
+ # Add op to the graph
171
+ op = str(node.target)
172
+ fx_inputs, attributes = _get_inputs_and_attributes(node)
173
+ inputs = []
174
+ for i, input_ in enumerate(fx_inputs):
175
+ if input_ is None:
176
+ inputs.append(None)
177
+ elif hasattr(input_, "name"):
178
+ inputs.append(values[input_.name])
179
+ else:
180
+ attributes[f"arg_{i}"] = input_
181
+
182
+ output_name = node.name
183
+ output = ir.Value(name=output_name)
184
+ _set_shape_type(output, node.meta["val"])
185
+
186
+ values[output_name] = output
187
+ ir_node = ir.Node(
188
+ "pkg.torch.ops",
189
+ op,
190
+ inputs,
191
+ attributes=ir_convenience.convert_attributes(attributes),
192
+ outputs=[output],
193
+ name=node.name,
194
+ )
195
+ ir_node.meta["node"] = node
196
+ graph.append(ir_node)
197
+
198
+ # Record the nn.Module stack for the node
199
+ _set_namespace(node, ir_node)
200
+ return values
201
+
202
+
203
+ def _torch_version_integer() -> int:
204
+ return int(torch.__version__.replace(".", ""))
205
+
206
+
207
+ def _get_inputs_and_attributes(
208
+ node: torch.fx.Node,
209
+ ) -> tuple[list[torch.fx.Node | None], dict[str, Any]]:
210
+ """Find and Fill in the not provided kwargs with default values."""
211
+
212
+ # TODO: aten::sym_size has overload, but fx graph is using
213
+ # overloadpacket for some reasons.
214
+ # https://github.com/pytorch/pytorch/issues/97201
215
+ # We manually assigned overload for aten::sym_size.
216
+ if hasattr(node.target, "_schema"):
217
+ node_schema = node.target._schema # type: ignore[union-attr]
218
+ else:
219
+ node_schema = torch.ops.aten.sym_size.int._schema # type: ignore[union-attr]
220
+
221
+ # This function assumes the order of arguments in FX op is the
222
+ # same as the order of arguments in TorchScript op.
223
+ inputs = []
224
+ attributes = {}
225
+
226
+ if inspect.isbuiltin(node.target):
227
+ inputs = list(node.args)
228
+ else:
229
+ for arg, schema_arg in zip(node.args, node_schema.arguments):
230
+ if arg is None or isinstance(arg, torch.fx.Node):
231
+ inputs.append(arg)
232
+ else:
233
+ attributes[schema_arg.name] = arg
234
+ for schema_arg in node_schema.arguments:
235
+ if schema_arg.name not in node.kwargs:
236
+ continue
237
+ if schema_arg.name in {
238
+ "layout",
239
+ "device",
240
+ "requires_grad",
241
+ "pin_memory",
242
+ "memory_format",
243
+ "implicit",
244
+ }:
245
+ attr = str(node.kwargs[schema_arg.name])
246
+ if schema_arg.name == "dtype":
247
+ attr = _torch_dtype_to_onnx_dtype(node.kwargs[schema_arg.name])
248
+ else:
249
+ attr = node.kwargs[schema_arg.name]
250
+
251
+ attributes[schema_arg.name] = attr
252
+
253
+ return inputs, attributes
254
+
255
+
256
+ def exported_program_to_ir_graph(exported_program: torch.export.ExportedProgram):
257
+ # TODO: Make it an Interpreter
258
+ graph = ir.Graph(
259
+ [],
260
+ [],
261
+ nodes=[],
262
+ opset_imports={"": 20, "pkg.torch.ops": _torch_version_integer()},
263
+ name="main_graph",
264
+ )
265
+
266
+ # TODO: We can call exported_program.graph.eliminate_dead_code()
267
+
268
+ # 1. Add all nodes to the graph and create a dictionary of values
269
+ values = _add_nodes(exported_program, graph)
270
+
271
+ # 2. Add user inputs and all parameters/buffers to the graph.
272
+ # Since the node names and the tensor names are different, we need to rename
273
+ # the nodes to match the tensor names later. For now we will just use the node names.
274
+ user_inputs = [
275
+ spec
276
+ for spec in exported_program.graph_signature.input_specs
277
+ if spec.kind == graph_signature.InputKind.USER_INPUT
278
+ ]
279
+ non_user_inputs = [
280
+ spec
281
+ for spec in exported_program.graph_signature.input_specs
282
+ if spec.kind != graph_signature.InputKind.USER_INPUT
283
+ ]
284
+
285
+ for spec in itertools.chain(user_inputs, non_user_inputs):
286
+ # Put the user inputs first and then the parameters/buffers
287
+ value_name = spec.arg.name
288
+ input_kind = spec.kind
289
+ persistent = spec.persistent
290
+ value = values[value_name]
291
+
292
+ value.metadata_props["pkg.torch.export.graph_signature.InputSpec.kind"] = (
293
+ input_kind.name
294
+ )
295
+ value.metadata_props[
296
+ "pkg.torch.export.graph_signature.InputSpec.persistent"
297
+ ] = str(persistent)
298
+
299
+ graph.inputs.append(value) # type: ignore
300
+ if input_kind != graph_signature.InputKind.USER_INPUT:
301
+ graph.initializers[value_name] = value
302
+
303
+ # 3. Add outputs to the graph. Keep the order of the outputs.
304
+ for spec in exported_program.graph_signature.output_specs:
305
+ value_name = spec.arg.name
306
+ output_kind = spec.kind
307
+ value = values[value_name]
308
+
309
+ value.metadata_props["pkg.torch.export.graph_signature.OutputSpec.kind"] = (
310
+ output_kind.name
311
+ )
312
+
313
+ if output_kind == graph_signature.OutputKind.USER_OUTPUT:
314
+ graph.outputs.append(value)
315
+
316
+ # 4. Rename the initializers to match the tensor names
317
+ for name, param_name in itertools.chain(
318
+ exported_program.graph_signature.inputs_to_parameters.items(),
319
+ exported_program.graph_signature.inputs_to_buffers.items(),
320
+ ):
321
+ initializer = graph.initializers.pop(name)
322
+ initializer.name = param_name
323
+ graph.initializers[param_name] = initializer
324
+
325
+ # 5. Add initializers to the graph
326
+ for name, value in graph.initializers.items():
327
+ torch_tensor = exported_program.state_dict.get(name)
328
+ if torch_tensor is None:
329
+ logger.warning("Tensor '%s' not found in state_dict", name)
330
+ continue
331
+ ir_tensor = TorchTensor(torch_tensor, name=name)
332
+ graph.initializers[name].const_value = ir_tensor
333
+ _set_shape_type(graph.initializers[name], torch_tensor)
334
+
335
+ # TODO: Decide if we should keep mutated buffers as inputs/outputs
336
+
337
+ return graph
338
+
339
+
340
+ def exported_program_to_ir(exported_program: torch.export.ExportedProgram) -> ir.Model:
341
+ return ir.Model(
342
+ exported_program_to_ir_graph(exported_program),
343
+ ir_version=9,
344
+ producer_name="torch",
345
+ producer_version=torch.__version__,
346
+ )
@@ -0,0 +1,44 @@
1
+ """Patch torch.onnx.export to use the exported program"""
2
+
3
+ import torch
4
+
5
+ from typing import Union, Any, Optional, Sequence, Mapping, Collection, Type
6
+ import io
7
+ import torch.export
8
+ import logging
9
+
10
+ logger = logging.Logger(__name__)
11
+
12
+
13
+ def torch_onnx_export_adaptor(
14
+ model: torch.nn.Module,
15
+ args: tuple[Any, ...],
16
+ f: Union[str, io.BytesIO],
17
+ export_params: bool = True,
18
+ verbose: bool = False,
19
+ training: torch.onnx.TrainingMode = torch.onnx.TrainingMode.EVAL,
20
+ input_names: Optional[Sequence[str]] = None,
21
+ output_names: Optional[Sequence[str]] = None,
22
+ operator_export_type: torch.onnx.OperatorExportTypes = torch.onnx.OperatorExportTypes.ONNX,
23
+ opset_version: Optional[int] = None,
24
+ do_constant_folding: bool = True,
25
+ dynamic_axes: Optional[
26
+ Union[Mapping[str, Mapping[int, str]], Mapping[str, Sequence[int]]]
27
+ ] = None,
28
+ keep_initializers_as_inputs: Optional[bool] = None,
29
+ custom_opsets: Optional[Mapping[str, int]] = None,
30
+ export_modules_as_functions: Union[bool, Collection[Type[torch.nn.Module]]] = False,
31
+ autograd_inlining: Optional[bool] = True,
32
+ **_,
33
+ ) -> None:
34
+ # Test: create an exported program first
35
+ if args and isinstance(args[-1], dict):
36
+ kwargs = args[-1]
37
+ args = args[:-1]
38
+ # TODO: Support dynamic shapes
39
+ program = torch.export.export(model, args, kwargs)
40
+ torch.onnx.dynamo_export(program, *args, **kwargs).save(f)
41
+
42
+
43
+ def patch_torch():
44
+ torch.onnx.export = torch_onnx_export_adaptor
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.1
2
+ Name: torch-onnx
3
+ Version: 0.0.1
4
+ Summary: Experimental tools for converting PyTorch models to ONNX
5
+ Author-email: Justin Chu <justinchu@microsoft.com>
6
+ License: MIT License
7
+ Project-URL: Repository, https://github.com/justinchuby/torch-onnx
8
+ Keywords: onnx,pytorch,converter,convertion,exporter
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: POSIX
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: License :: OSI Approved :: MIT License
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: torch
25
+ Requires-Dist: onnxscript
26
+ Requires-Dist: onnx
27
+
28
+ # PyTorch to ONNX Exporter
29
+
30
+ Experimental torch ONNX exporter.
31
+
32
+ > [!WARNING]
33
+ > This is an experimental project and is not designed for production use.
34
+ > Use `torch.onnx.export` for these purposes.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install torch-onnx
40
+ ```
41
+
42
+ ## Usage
43
+
44
+ ```python
45
+ import torch
46
+ import torch_onnx
47
+ from onnxscript import ir
48
+ import onnx
49
+
50
+ # Get an exported program with torch.export
51
+ exported = torch.export.export(...)
52
+ model = torch_onnx.exported_program_to_ir(exported)
53
+ proto = ir.to_proto(model)
54
+ # This will give you an ATen dialect graph (un-lowered ONNX graph with ATen ops)
55
+ onnx.save(proto, "model.onnx")
56
+ ```
57
+
58
+ ## Design
59
+
60
+ {ExportedProgram, jit} -> {ONNX IR} -> {torchlib} -> {ONNX}
61
+
62
+ - Flat graph; Scope info as metadata, not functions
63
+ - Because existing tools are not good at handling them
64
+ - Eager optimization where appropriate
65
+ - Because exsiting tools are not good at optimizing
66
+ - Drop in replacement for torch.onnx.export
67
+ - Minimum migration effort
68
+ - Use ExportedProgram
69
+ - Rely on robustness of the torch.export implementation
70
+ - This does not solve dynamo limitations, but it avoids introducing additional breakage by running fx passes
71
+ - Build graph eagerly, in place
72
+ - Expose shape and dtype information to the op functions; build with IR
73
+
74
+ ## Why is this doable?
75
+
76
+ - We need to verify torch.export coverage on Huggingface Optimum https://github.com/huggingface/optimum/tree/main/optimum/exporters/onnx; and they are not patching torch.onnx itself.
77
+ - Path torch.onnx.export such that packages do not need to change a single line to use dynamo
78
+ - We have all operators implemented and portable
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/torch_onnx/__init__.py
5
+ src/torch_onnx/_core.py
6
+ src/torch_onnx/_patch.py
7
+ src/torch_onnx.egg-info/PKG-INFO
8
+ src/torch_onnx.egg-info/SOURCES.txt
9
+ src/torch_onnx.egg-info/dependency_links.txt
10
+ src/torch_onnx.egg-info/requires.txt
11
+ src/torch_onnx.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ torch
2
+ onnxscript
3
+ onnx
@@ -0,0 +1 @@
1
+ torch_onnx