forked from Rajeevveera24/pytorch-copy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1990 lines (1691 loc) · 76.8 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: allow-untyped-defs
"""Functions to export models into the ONNX IR format.
These models can be loaded with the ONNX library and then
converted to models which run on other deep learning frameworks.
"""
from __future__ import annotations
import contextlib
import copy
import inspect
import re
import typing
import warnings
from typing import Any, Callable, cast, Collection, Mapping, Sequence
import torch
import torch._C._onnx as _C_onnx
import torch.jit._trace
import torch.serialization
from torch import _C
from torch.onnx import ( # noqa: F401
_constants,
_deprecation,
_exporter_states,
errors,
symbolic_helper,
)
from torch.onnx._globals import GLOBALS
from torch.onnx._internal import diagnostics, jit_utils, onnx_proto_utils, registration
__all__ = [
"is_in_onnx_export",
"select_model_mode_for_export",
"disable_apex_o2_state_dict_hook",
"setup_onnx_logging",
"exporter_context",
"export",
"model_signature",
"warn_on_static_input_change",
"unpack_quantized_tensor",
"export_to_pretty_string",
"unconvertible_ops",
"register_custom_op_symbolic",
"unregister_custom_op_symbolic",
]
def is_in_onnx_export() -> bool:
"""Returns whether it is in the middle of ONNX export."""
return GLOBALS.in_onnx_export
# TODO(justinchuby): Remove dependency to this global variable from constant_fold.cpp
# Skip check due to cannot import IValue from torch._C
_params_dict = {} # type: ignore[var-annotated]
@contextlib.contextmanager
def select_model_mode_for_export(model, mode: _C_onnx.TrainingMode):
r"""A context manager to temporarily set the training mode of ``model``
to ``mode``, resetting it when we exit the with-block.
Args:
model: Same type and meaning as ``model`` arg to :func:`export`.
mode: Same type and meaning as ``training`` arg to :func:`export`.
"""
if not isinstance(mode, _C_onnx.TrainingMode):
raise TypeError(
f"'mode' should be a torch.onnx.TrainingMode enum, but got '{type(mode)}'."
)
originally_training: bool = False
if hasattr(model, "training"):
originally_training = model.training
# ONNX opset 12 has better support for training amenable models, with updated
# versions of the dropout and batch_norm operators
if mode == _C_onnx.TrainingMode.TRAINING or (
mode == _C_onnx.TrainingMode.PRESERVE and originally_training
):
GLOBALS.export_training = True
if GLOBALS.export_onnx_opset_version < 12:
warnings.warn(
"You are exporting the model in training mode with onnx opset "
f"version {GLOBALS.export_onnx_opset_version}. "
"Opset versions lower than opset 12 will not be able to export "
"nodes such as Dropout and BatchNorm correctly."
)
else:
GLOBALS.export_training = False
GLOBALS.training_mode = mode
if mode == _C_onnx.TrainingMode.TRAINING:
model.train(True)
elif mode == _C_onnx.TrainingMode.EVAL:
model.train(False)
# else mode == _C_onnx.TrainingMode.PRESERVE, do nothing
try:
yield
finally:
if hasattr(model, "training") and not mode == _C_onnx.TrainingMode.PRESERVE:
model.train(originally_training)
@contextlib.contextmanager
def disable_apex_o2_state_dict_hook(model: torch.nn.Module | torch.jit.ScriptFunction):
# Apex O2 hook state_dict to return fp16 weights as fp32.
# Exporter cannot identify them as same tensors.
# Since this hook is only used by optimizer, it is safe to
# remove this hook while exporting.
if not isinstance(model, torch.jit.ScriptFunction):
model_hooks = {} # type: ignore[var-annotated]
for module in model.modules():
for key, hook in module._state_dict_hooks.items():
if type(hook).__name__ == "O2StateDictHook":
if module not in model_hooks:
model_hooks[module] = {}
model_hooks[module][key] = hook
if module in model_hooks:
for key in model_hooks[module]:
module._state_dict_hooks.pop(key)
try:
yield
finally:
# Add the hooks back
for module, m_map in model_hooks.items():
for key, hook in m_map.items():
module._state_dict_hooks[key] = hook
else:
try:
yield
finally:
pass
@contextlib.contextmanager
def setup_onnx_logging(verbose: bool):
is_originally_enabled = torch.onnx.is_onnx_log_enabled()
if is_originally_enabled or verbose:
torch.onnx.enable_log()
try:
yield
finally:
if not is_originally_enabled:
torch.onnx.disable_log()
@contextlib.contextmanager
def exporter_context(model, mode: _C_onnx.TrainingMode, verbose: bool):
with select_model_mode_for_export(
model, mode
) as mode_ctx, disable_apex_o2_state_dict_hook(
model
) as apex_ctx, setup_onnx_logging(
verbose
) as log_ctx, diagnostics.create_export_diagnostic_context() as diagnostic_ctx:
yield (mode_ctx, apex_ctx, log_ctx, diagnostic_ctx)
def _get_torch_export_args(
args: tuple[Any, ...],
kwargs: dict[str, Any] | None,
) -> tuple[tuple[Any, ...], dict[str, Any] | None]:
"""Obtain the arguments for torch.onnx.export from the model and the input arguments."""
if not kwargs and args and isinstance(args[-1], dict):
kwargs = args[-1]
args = args[:-1]
return args, kwargs
def export(
model: torch.nn.Module | torch.jit.ScriptModule | torch.jit.ScriptFunction,
args: tuple[Any, ...] | torch.Tensor,
f: str,
*,
kwargs: dict[str, Any] | None = None,
export_params: bool = True,
verbose: bool = False,
training: _C_onnx.TrainingMode = _C_onnx.TrainingMode.EVAL,
input_names: Sequence[str] | None = None,
output_names: Sequence[str] | None = None,
operator_export_type: _C_onnx.OperatorExportTypes = _C_onnx.OperatorExportTypes.ONNX,
opset_version: int | None = None,
do_constant_folding: bool = True,
dynamic_axes: Mapping[str, Mapping[int, str]]
| Mapping[str, Sequence[int]]
| None = None,
keep_initializers_as_inputs: bool | None = None,
custom_opsets: Mapping[str, int] | None = None,
export_modules_as_functions: bool | Collection[type[torch.nn.Module]] = False,
autograd_inlining: bool = True,
) -> None:
r"""Exports a model into ONNX format.
If ``model`` is not a :class:`torch.jit.ScriptModule` nor a
:class:`torch.jit.ScriptFunction`, this runs
``model`` once in order to convert it to a TorchScript graph to be exported
(the equivalent of :func:`torch.jit.trace`). Thus this has the same limited support
for dynamic control flow as :func:`torch.jit.trace`.
Args:
model: The model to be exported.
args:
args can be structured either as:
1. ONLY A TUPLE OF ARGUMENTS::
args = (x, y, z)
The tuple should contain model inputs such that ``model(*args)`` is a valid
invocation of the model. Any non-Tensor arguments will be hard-coded into the
exported model; any Tensor arguments will become inputs of the exported model,
in the order they occur in the tuple.
2. A TENSOR::
args = torch.Tensor([1])
This is equivalent to a 1-ary tuple of that Tensor.
3. A TUPLE OF ARGUMENTS ENDING WITH A DICTIONARY OF NAMED ARGUMENTS::
args = (x, {"y": input_y, "z": input_z})
All but the last element of the tuple will be passed as non-keyword arguments,
and named arguments will be set from the last element. If a named argument is
not present in the dictionary, it is assigned the default value, or None if a
default value is not provided.
.. warning::
This behavior will be deprecated in a future release. Please use the
kwargs argument instead.
.. note::
If a dictionary is the last element of the args tuple, it will be
interpreted as containing named arguments. In order to pass a dict as the
last non-keyword arg, provide an empty dict as the last element of the args
tuple. For example, instead of::
torch.onnx.export(
model,
(
x,
# WRONG: will be interpreted as named arguments
{y: z},
),
"test.onnx.pb",
)
Write::
torch.onnx.export(model, (x, {y: z}, {}), "test.onnx.pb")
f: Path to the output ONNX model file. E.g. "model.onnx".
kwargs: Named arguments to the model.
export_params: If True, all parameters will
be exported. Set this to False if you want to export an untrained model.
In this case, the exported model will first take all of its parameters
as arguments, with the ordering as specified by ``model.state_dict().values()``
verbose: if True, prints a description of the
model being exported to stdout. In addition, the final ONNX graph will include the
field ``doc_string``` from the exported model which mentions the source code locations
for ``model``. If True, ONNX exporter logging will be turned on.
training:
* ``TrainingMode.EVAL``: export the model in inference mode.
* ``TrainingMode.PRESERVE``: export the model in inference mode if model.training is
False and in training mode if model.training is True.
* ``TrainingMode.TRAINING``: export the model in training mode. Disables optimizations
which might interfere with training.
input_names (list of str, default empty list): names to assign to the
input nodes of the graph, in order.
output_names (list of str, default empty list): names to assign to the
output nodes of the graph, in order.
operator_export_type (enum, default OperatorExportTypes.ONNX):
.. warning::
This option will be deprecated in a future release. Future exported
graphs will always use the default opset domain.
* ``OperatorExportTypes.ONNX``: Export all ops as regular ONNX ops
(in the default opset domain).
* ``OperatorExportTypes.ONNX_FALLTHROUGH``: Try to convert all ops
to standard ONNX ops in the default opset domain. If unable to do so
(e.g. because support has not been added to convert a particular torch op to ONNX),
fall back to exporting the op into a custom opset domain without conversion. Applies
to `custom ops <https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html>`_
as well as ATen ops. For the exported model to be usable, the runtime must support
these non-standard ops.
* ``OperatorExportTypes.ONNX_ATEN``: All ATen ops (in the TorchScript namespace "aten")
are exported as ATen ops (in opset domain "org.pytorch.aten").
`ATen <https://pytorch.org/cppdocs/#aten>`_ is PyTorch's built-in tensor library, so
this instructs the runtime to use PyTorch's implementation of these ops.
.. warning::
Models exported this way are probably runnable only by Caffe2.
This may be useful if the numeric differences in implementations of operators are
causing large differences in behavior between PyTorch and Caffe2 (which is more
common on untrained models).
* ``OperatorExportTypes.ONNX_ATEN_FALLBACK``: Try to export each ATen op
(in the TorchScript namespace "aten") as a regular ONNX op. If we are unable to do so
(e.g. because support has not been added to convert a particular torch op to ONNX),
fall back to exporting an ATen op. See documentation on OperatorExportTypes.ONNX_ATEN for
context.
For example::
graph(%0 : Float):
%3 : int = prim::Constant[value=0]()
# conversion unsupported
%4 : Float = aten::triu(%0, %3)
# conversion supported
%5 : Float = aten::mul(%4, %0)
return (%5)
Assuming ``aten::triu`` is not supported in ONNX, this will be exported as::
graph(%0 : Float):
%1 : Long() = onnx::Constant[value={0}]()
# not converted
%2 : Float = aten::ATen[operator="triu"](%0, %1)
# converted
%3 : Float = onnx::Mul(%2, %0)
return (%3)
.. warning::
Models exported this way are probably runnable only by Caffe2.
opset_version (int, default 17): The version of the
`default (ai.onnx) opset <https://github.com/onnx/onnx/blob/master/docs/Operators.md>`_
to target. Must be >= 7 and <= 17.
do_constant_folding: Apply the constant-folding optimization.
Constant-folding will replace some of the ops that have all constant inputs
with pre-computed constant nodes.
dynamic_axes:
By default the exported model will have the shapes of all input and output tensors
set to exactly match those given in ``args``. To specify axes of tensors as
dynamic (i.e. known only at run-time), set ``dynamic_axes`` to a dict with schema:
* KEY (str): an input or output name. Each name must also be provided in ``input_names`` or
``output_names``.
* VALUE (dict or list): If a dict, keys are axis indices and values are axis names. If a
list, each element is an axis index.
For example::
class SumModule(torch.nn.Module):
def forward(self, x):
return torch.sum(x, dim=1)
torch.onnx.export(
SumModule(),
(torch.ones(2, 2),),
"onnx.pb",
input_names=["x"],
output_names=["sum"],
)
Produces::
input {
name: "x"
...
shape {
dim {
dim_value: 2 # axis 0
}
dim {
dim_value: 2 # axis 1
...
output {
name: "sum"
...
shape {
dim {
dim_value: 2 # axis 0
...
While::
torch.onnx.export(
SumModule(),
(torch.ones(2, 2),),
"onnx.pb",
input_names=["x"],
output_names=["sum"],
dynamic_axes={
# dict value: manually named axes
"x": {0: "my_custom_axis_name"},
# list value: automatic names
"sum": [0],
},
)
Produces::
input {
name: "x"
...
shape {
dim {
dim_param: "my_custom_axis_name" # axis 0
}
dim {
dim_value: 2 # axis 1
...
output {
name: "sum"
...
shape {
dim {
dim_param: "sum_dynamic_axes_1" # axis 0
...
keep_initializers_as_inputs: If True, all the
initializers (typically corresponding to parameters) in the
exported graph will also be added as inputs to the graph. If False,
then initializers are not added as inputs to the graph, and only
the non-parameter inputs are added as inputs.
This may allow for better optimizations (e.g. constant folding) by
backends/runtimes.
If True, `deduplicate_initializers` pass will not be executed. This means
initializers with duplicated values will not be deduplicated and
will be treated as distinct inputs to the graph. This allows different
input initializers to be supplied at the runtime following export.
If ``opset_version < 9``, initializers MUST be part of graph
inputs and this argument will be ignored and the behavior will be
equivalent to setting this argument to True.
custom_opsets (dict[str, int], default empty dict): A dict with schema:
* KEY (str): opset domain name
* VALUE (int): opset version
If a custom opset is referenced by ``model`` but not mentioned in this dictionary,
the opset version is set to 1. Only custom opset domain name and version should be
indicated through this argument.
export_modules_as_functions: Flag to enable
exporting all ``nn.Module`` forward calls as local functions in ONNX. Or a set to indicate the
particular types of modules to export as local functions in ONNX.
This feature requires ``opset_version`` >= 15, otherwise the export will fail. This is because
``opset_version`` < 15 implies IR version < 8, which means no local function support.
Module variables will be exported as function attributes. There are two categories of function
attributes.
1. Annotated attributes: class variables that have type annotations via
`PEP 526-style <https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations>`_
will be exported as attributes.
Annotated attributes are not used inside the subgraph of ONNX local function because
they are not created by PyTorch JIT tracing, but they may be used by consumers
to determine whether or not to replace the function with a particular fused kernel.
2. Inferred attributes: variables that are used by operators inside the module. Attribute names
will have prefix "inferred::". This is to differentiate from predefined attributes retrieved from
python module annotations. Inferred attributes are used inside the subgraph of ONNX local function.
* ``False`` (default): export ``nn.Module`` forward calls as fine grained nodes.
* ``True``: export all ``nn.Module`` forward calls as local function nodes.
* Set of type of nn.Module: export ``nn.Module`` forward calls as local function nodes,
only if the type of the ``nn.Module`` is found in the set.
autograd_inlining: Flag used to control whether to inline autograd functions.
Refer to https://github.com/pytorch/pytorch/pull/74765 for more details.
Raises:
:class:`torch.onnx.errors.CheckerError`: If the ONNX checker detects an invalid ONNX graph.
:class:`torch.onnx.errors.UnsupportedOperatorError`: If the ONNX graph cannot be exported because it
uses an operator that is not supported by the exporter.
:class:`torch.onnx.errors.OnnxExporterError`: Other errors that can occur during export.
All errors are subclasses of :class:`errors.OnnxExporterError`.
"""
if operator_export_type != _C_onnx.OperatorExportTypes.ONNX:
warnings.warn(
"Setting `operator_export_type` to something other than default is deprecated. "
"The option will be removed in a future release.",
category=FutureWarning,
)
if training == _C_onnx.TrainingMode.TRAINING:
warnings.warn(
"Setting `training` to something other than default is deprecated. "
"The option will be removed in a future release. Please set the training mode "
"before exporting the model.",
category=FutureWarning,
)
args = (args,) if isinstance(args, torch.Tensor) else args
if kwargs is not None:
args = args + (kwargs,)
_export(
model,
args,
f,
export_params,
verbose,
training,
input_names,
output_names,
operator_export_type=operator_export_type,
opset_version=opset_version,
do_constant_folding=do_constant_folding,
dynamic_axes=dynamic_axes,
keep_initializers_as_inputs=keep_initializers_as_inputs,
custom_opsets=custom_opsets,
export_modules_as_functions=export_modules_as_functions,
autograd_inlining=autograd_inlining,
)
return None
def _is_constant_tensor_list(node):
if node.kind() != "prim::Constant":
return False
output_type = node.output().type()
if output_type.isSubtypeOf(_C.ListType.ofTensors()):
return True
if output_type.isSubtypeOf(_C.ListType(_C.OptionalType.ofTensor())):
return True
# ONNX can't handle constants that are lists of tensors, which can
# get generated in constant prop. So we split them back into prim::ListConstructs
def _split_tensor_list_constants(g, block):
for node in block.nodes():
for subblock in node.blocks():
_split_tensor_list_constants(g, subblock)
if _is_constant_tensor_list(node):
inputs = []
for val in node.output().toIValue():
input = g.insertConstant(val)
input.node().moveBefore(node)
input.node().copyMetadata(node)
inputs.append(input)
lc = (
g.create("prim::ListConstruct", inputs)
.insertBefore(node)
.output()
.setType(_C.ListType.ofTensors())
)
lc.node().copyMetadata(node)
node.output().replaceAllUsesWith(lc)
def _optimize_graph(
graph: _C.Graph,
operator_export_type: _C_onnx.OperatorExportTypes,
_disable_torch_constant_prop: bool = False,
fixed_batch_size: bool = False,
params_dict=None,
dynamic_axes=None,
input_names=None,
module=None,
):
if params_dict is None:
params_dict = {}
# Inline everything
_C._jit_pass_inline(graph)
# Remove fork/wait nodes
_C._jit_pass_inline_fork_wait(graph)
_C._jit_pass_lint(graph)
if GLOBALS.autograd_inlining:
_C._jit_pass_onnx_autograd_function_process(graph)
_C._jit_pass_lower_all_tuples(graph)
# we now record some ops like ones/zeros
# into a trace where we previously recorded constants.
# use constant prop to maintain our current level of onnx support
# without implementing symbolics for all of them
if _disable_torch_constant_prop is False:
_C._jit_pass_constant_propagation(graph)
_split_tensor_list_constants(graph, graph)
# run dce to eliminate dead parts of the graph that might have been
# left behind by things like symbolic_override
_C._jit_pass_dce(graph)
_C._jit_pass_lint(graph)
# CSE should improve perf when Autocast is used with disabled cache
# Autocast is disabled due to a limitation on tracer as described at https://github.com/pytorch/pytorch/issues/84092
# Must run before _C._jit_pass_erase_number_types to prevent type substitution
if _C._jit_pass_cse(graph):
_C._jit_pass_onnx_lint(graph)
_C._jit_pass_canonicalize_graph_fuser_ops(graph)
_C._jit_pass_lint(graph)
_C._jit_pass_peephole(graph, True)
_C._jit_pass_fuse_addmm(graph)
_C._jit_pass_lint(graph)
_C._jit_pass_peephole(graph, True)
_C._jit_pass_lower_all_tuples(graph)
# in _jit_pass_onnx, symbolic functions are called for each node for conversion.
# However, there are nodes that cannot be converted without additional context.
# For example, the number of outputs from split (and whether it is static or dynamic) is unknown
# until the point where it is unpacked by listUnpack node.
# This pass does a preprocess, and prepares the nodes such that enough context can be received
# by the symbolic function.
_C._jit_pass_onnx_remove_inplace_ops_for_onnx(graph, module)
_C._jit_pass_onnx_preprocess(graph)
# onnx does not support tuples, so try to remove them
_C._jit_pass_lint(graph)
# onnx only supports tensors, but 1 / 2 = 0.5 and tensor(1) / tensor(2) = 0
_C._jit_pass_prepare_division_for_onnx(graph)
_C._jit_pass_onnx_remove_print(graph)
_C._jit_pass_onnx_preprocess_caffe2(graph)
symbolic_helper._quantized_ops.clear()
# Unpack quantized weights for conv and linear ops and insert into graph.
_C._jit_pass_onnx_unpack_quantized_weights(graph, params_dict)
# onnx only supports tensors, so we turn all out number types into tensors
_C._jit_pass_erase_number_types(graph)
if GLOBALS.onnx_shape_inference:
input_names = [] if input_names is None else input_names
dynamic_axes = {} if dynamic_axes is None else dynamic_axes
_C._jit_pass_onnx_set_dynamic_input_shape(graph, dynamic_axes, input_names)
_C._jit_pass_onnx_lint(graph)
graph = _C._jit_pass_onnx(graph, operator_export_type)
_C._jit_pass_onnx_lint(graph)
_C._jit_pass_lint(graph)
_C._jit_pass_onnx_scalar_type_analysis(
graph, True, GLOBALS.export_onnx_opset_version
)
_C._jit_pass_lint(graph)
_C._jit_pass_onnx_peephole(
graph, GLOBALS.export_onnx_opset_version, fixed_batch_size
)
_C._jit_pass_lint(graph)
# graph is not a valid jit graph anymore because types have been replaced
# (e.g. int with Tensor), so it now contains operators that don't actually
# exist. We can't run normal dead code elimination because it'd fail trying
# to look up if an operator has side effects, but we can run a dead code
# elimination variant that doesn't need to look up if an op has side effects.
_C._jit_pass_dce_allow_deleting_nodes_with_side_effects(graph)
_C._jit_pass_lint(graph)
graph = _C._jit_pass_canonicalize(graph)
_C._jit_pass_lint(graph)
if GLOBALS.onnx_shape_inference:
_C._jit_pass_onnx_graph_shape_type_inference(
graph, params_dict, GLOBALS.export_onnx_opset_version
)
return graph
def warn_on_static_input_change(input_states):
"""Warns that changes to input dictionaries and strings won't take effect in the traced ONNX graph.
We accept dictionaries and strings as ONNX inputs, but they should be only for
configuration use. we detect here if these inputs are modified, and if so we warn
the user that the changes won't take effect in the traced ONNX graph.
"""
for input, traced_input in zip(input_states[0], input_states[1]):
if isinstance(input, dict):
if list(input.keys()) != list(traced_input.keys()):
warning = (
"We detected that you are modifying a dictionary that is an input to your "
"model. "
"Note that dictionaries are allowed as inputs in ONNX but they should be "
"handled with care. "
"Usages of dictionaries is not recommended, and should not be used except "
"for configuration use. "
"Also note that the order and values of the keys must remain the same. "
)
warnings.warn(warning)
elif isinstance(input, str):
if input != traced_input:
warning = (
"The model seems to have string inputs/outputs. "
"Note that strings will not appear as inputs/outputs of the ONNX graph. "
)
warnings.warn(warning)
def _resolve_args_by_export_type(arg_name, arg_value, operator_export_type):
"""Resolves the arguments that are ignored when export_type != operator_export_type.ONNX."""
return arg_value
def _decide_keep_init_as_input(
keep_initializers_as_inputs: bool | None,
operator_export_type: _C_onnx.OperatorExportTypes,
opset_version: int,
):
"""Decides whether the initializers in the graph should be listed as ONNX graph inputs.
This method encapsulates the logic to decide whether the initializers in the graph
should be listed as ONNX graph inputs (i.e., whether to choose ONNX IR v3 or v4).
If keep_initializers_as_inputs is not specified (None), then we decide whether to keep
initializers as graph inputs (val_keep_init_as_ip) based on export type. If export type
is ONNX, then do not keep initializers as input (val_keep_init_as_ip=False). For all other
export types keep initializers as input (val_keep_init_as_ip=True).
If keep_initializers_as_inputs is specified, then respect it. Unless opset version <= 8,
in which case it must be ignored because for opset version <= 8, all initializers MUST be
part of graph input (only ONNX IR v3 is allowed), i.e. val_keep_init_as_ip=True.
Special handling is needed for opset version 8 or lower, because irrespective
of user input for keep_initializers_as_inputs, the graph must follow ONNX IR v3
semantics, i.e. all initializers must be listed as ONNX graph input.
"""
if opset_version < 9:
if keep_initializers_as_inputs is False:
warnings.warn(
"Setting 'keep_initializers_as_inputs=False' for opset version"
"8 or lower would lead to an invalid ONNX graph. Therefore, "
"'keep_initializers_as_inputs=False' is ignored during export."
"Exported model will have initializers as graph inputs (compliant "
" to ONNX IR v3)."
)
return True # i.e. True == initializers are part of graph input (ONNX IR v3)
val_keep_init_as_ip = (
True if keep_initializers_as_inputs is None else keep_initializers_as_inputs
)
if (
keep_initializers_as_inputs is None
and operator_export_type is _C_onnx.OperatorExportTypes.ONNX
):
val_keep_init_as_ip = False
return val_keep_init_as_ip
def _decide_add_node_names(add_node_names, operator_export_type):
return _resolve_args_by_export_type(
"add_node_names", add_node_names, operator_export_type
)
def _decide_constant_folding(do_constant_folding, operator_export_type, training):
do_constant_folding = _resolve_args_by_export_type(
"do_constant_folding", do_constant_folding, operator_export_type
)
if do_constant_folding and (
training is not None and training is not _C_onnx.TrainingMode.EVAL
):
warnings.warn(
"It is recommended that constant folding be turned off ('do_constant_folding=False') "
"when exporting the model in training-amenable mode, i.e. with 'training=TrainingMode.TRAIN' "
"or 'training=TrainingMode.PRESERVE' (when model is in training mode). Otherwise, some "
"learnable model parameters may not translate correctly in the exported ONNX model "
"because constant folding mutates model parameters. Please consider "
"turning off constant folding or setting the training=TrainingMode.EVAL."
)
return do_constant_folding
def _signature(model) -> inspect.Signature:
should_be_callable = getattr(model, "forward", model)
if callable(should_be_callable):
return inspect.signature(should_be_callable)
raise ValueError("model has no forward method and is not callable")
def _decide_input_format(model, args):
try:
sig = _signature(model)
except ValueError as e:
warnings.warn(f"{e}, skipping _decide_input_format")
return args
try:
ordered_list_keys = list(sig.parameters.keys())
if ordered_list_keys[0] == "self":
ordered_list_keys = ordered_list_keys[1:]
args_dict: dict = {}
if isinstance(args, list):
args_list = args
elif isinstance(args, tuple):
args_list = list(args)
else:
args_list = [args]
if isinstance(args_list[-1], dict):
args_dict = args_list[-1]
args_list = args_list[:-1]
n_nonkeyword = len(args_list)
for optional_arg in ordered_list_keys[n_nonkeyword:]:
if optional_arg in args_dict:
args_list.append(args_dict[optional_arg])
# Check if this arg has a default value
else:
param = sig.parameters[optional_arg]
if param.default != param.empty:
args_list.append(param.default)
args = args_list if isinstance(args, list) else tuple(args_list)
# Cases of models with no input args
except IndexError:
warnings.warn("No input args, skipping _decide_input_format")
except Exception as e:
warnings.warn(f"Skipping _decide_input_format\n {e.args[0]}")
return args
def _from_dynamic_axes_to_dynamic_shapes(
model,
dynamic_axes: Mapping[str, Mapping[int, str]]
| Mapping[str, Sequence[int]]
| None = None,
input_names: Sequence[str] | None = None,
) -> dict[str, Any] | None:
"""
dynamic_axes examples:
(1) dynamic_axes = {"x": {0: "my_custom_axis_name_1"}, "y": {1: "my_custom_axis_name_2"}}
(2) dynamic_axes = {"x": [0], "y": [1]}
these will be converted to dynamic_shapes respectively:
(1) dynamic_shapes = {"x": {0: Dim("my_custom_axis_name_1")}, "y": {1: Dim("my_custom_axis_name_2")}}
(2) dynamic_shapes = {"x": {0: Dim("x_dim_0")}, "y": {1: Dim("y_dim_1")}} # auto-generated dim names
"""
if dynamic_axes is None:
return None
if input_names is None:
input_names_set = set()
else:
input_names_set = set(input_names)
dynamic_shapes: dict[str, Any | None] = {}
for input_name, axes in dynamic_axes.items():
if input_name in input_names_set:
raise ValueError(
"Assinging new input names is not supported yet. Please use model forward signature "
"to specify input names in dynamix_axes."
)
if isinstance(axes, dict):
dynamic_shapes[input_name] = {
k: torch.export.Dim(v) for k, v in axes.items()
}
elif isinstance(axes, list):
dynamic_shapes[input_name] = {
k: torch.export.Dim(f"{input_name}_dim_{k}") for k in axes
}
else:
raise TypeError(
f"dynamic_axes value must be either a dict or a list, but got {type(axes)}"
)
# torch.export.export needs static dim to present in dynamic_shapes
# for all input tensors, so we need to add them with None
try:
sig = _signature(model)
except ValueError as e:
warnings.warn(f"{e}, skipping auto filling None on static axes...")
return dynamic_shapes
for input_name in sig.parameters.keys():
if input_name not in dynamic_shapes:
dynamic_shapes[input_name] = None
return dynamic_shapes
def _trace(func, args, operator_export_type, return_outs=False):
# Special case for common case of passing a single Tensor
if isinstance(args, torch.Tensor):
args = (args,)
trace_graph, torch_out, inputs_states = torch.jit._get_trace_graph(
func,
args,
strict=False,
_force_outplace=False,
_return_inputs_states=True,
)
warn_on_static_input_change(inputs_states)
trace_graph = _optimize_graph(trace_graph, operator_export_type, params_dict={})
if return_outs:
return trace_graph, torch_out
return trace_graph
def _trace_and_get_graph_from_model(model, args):
# A basic sanity check: make sure the state_dict keys are the same
# before and after running the model. Fail fast!
orig_state_dict_keys = torch.jit._unique_state_dict(model).keys()
# Disable Autocast cache because it replaces kernel's weight and bias
# by (undesired) constants.
# No perf impact for when there are reused weights since https://github.com/pytorch/pytorch/pull/85665
prev_autocast_cache_enabled = torch.is_autocast_cache_enabled()
torch.set_autocast_cache_enabled(False)
trace_graph, torch_out, inputs_states = torch.jit._get_trace_graph(
model,
args,
strict=False,
_force_outplace=False,
_return_inputs_states=True,
)
torch.set_autocast_cache_enabled(prev_autocast_cache_enabled)
warn_on_static_input_change(inputs_states)
if orig_state_dict_keys != torch.jit._unique_state_dict(model).keys():
raise RuntimeError(
"state_dict changed after running the tracer; "
"something weird is happening in your model!"
)
return trace_graph, torch_out
def _get_param_count_list(method_graph, args_params):
param_count_list = []
for input_, arg_params_ in zip(method_graph.inputs(), args_params):
if "PackedParams" in str(input_.type()):
in_vars, _ = torch.jit._flatten(arg_params_)
param_count_list.append(len(in_vars))
else:
param_count_list.append(arg_params_ is not None)
return param_count_list
def _check_flatten_did_not_remove(original, jit_flattened):
"""torch.jit._flatten removes None. Check if it did so in this case."""
def flatten(x):
if isinstance(x, (list, tuple)):
for inner in x:
yield from flatten(inner)
elif isinstance(x, dict):
for inner in x.values():
yield from flatten(inner)
else:
yield x
flattened_with_none = list(flatten(original))
num_none = len(flattened_with_none) - len(jit_flattened)
assert num_none >= 0
if num_none:
raise ValueError(
f"args contained {num_none} None's after flattening. "
"When exporting a ScriptModule or ScriptFunction, no args may "
"be None because that breaks type propagation."
)
def _create_jit_graph(
model: torch.nn.Module | torch.jit.ScriptFunction, args: Sequence[Any]
) -> tuple[_C.Graph, list[_C.IValue], Any | None, _C.ScriptModule | None]:
if isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule)):
flattened_args = tuple(torch.jit._flatten(tuple(args))[0])
_check_flatten_did_not_remove(args, flattened_args)
torch_out = None
if isinstance(model, torch.jit.ScriptModule):
try:
graph = model.forward.graph # type: ignore[attr-defined]
except AttributeError as e:
raise RuntimeError("'forward' method must be a script method") from e
_C._jit_pass_onnx_function_substitution(graph)
freezed_module = _C._freeze_module(
cast(_C.ScriptModule, model._c), preserveParameters=True
)
module, params = _C._jit_onnx_list_model_parameters(freezed_module)
method_graph = module._get_method("forward").graph
args_params = tuple(args) + tuple(params)
param_count_list = _get_param_count_list(method_graph, args_params)
in_vars, _ = torch.jit._flatten(args_params)
graph = _C._propagate_and_assign_input_shapes(
method_graph, tuple(in_vars), param_count_list, False, False
)
return graph, params, torch_out, module
# torch.jit.ScriptFunction
params = []
graph = model.graph
_C._jit_pass_onnx_function_substitution(graph)
param_count_list = _get_param_count_list(graph, args)
graph = _C._propagate_and_assign_input_shapes(
graph, flattened_args, param_count_list, False, False
)
return graph, params, torch_out, None
graph, torch_out = _trace_and_get_graph_from_model(model, args)
_C._jit_pass_onnx_lint(graph)
state_dict = torch.jit._unique_state_dict(model)
params = list(state_dict.values())