utils.py 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. """Functions to export models into the ONNX IR format.
  2. These models can be loaded with the ONNX library and then
  3. converted to models which run on other deep learning frameworks.
  4. """
  5. from __future__ import annotations
  6. import contextlib
  7. import copy
  8. import inspect
  9. import io
  10. import re
  11. import textwrap
  12. import typing
  13. import warnings
  14. from typing import (
  15. Any,
  16. Callable,
  17. cast,
  18. Collection,
  19. Dict,
  20. List,
  21. Mapping,
  22. Optional,
  23. Sequence,
  24. Set,
  25. Tuple,
  26. Type,
  27. Union,
  28. )
  29. import torch
  30. import torch._C._onnx as _C_onnx
  31. import torch.jit._trace
  32. import torch.serialization
  33. from torch import _C
  34. from torch.onnx import ( # noqa: F401
  35. _constants,
  36. _exporter_states,
  37. errors,
  38. symbolic_caffe2,
  39. symbolic_helper,
  40. )
  41. from torch.onnx._globals import GLOBALS
  42. from torch.onnx._internal import (
  43. _beartype,
  44. diagnostics,
  45. jit_utils,
  46. onnx_proto_utils,
  47. registration,
  48. )
  49. __all__ = [
  50. "is_in_onnx_export",
  51. "select_model_mode_for_export",
  52. "disable_apex_o2_state_dict_hook",
  53. "setup_onnx_logging",
  54. "exporter_context",
  55. "export",
  56. "warn_on_static_input_change",
  57. "unpack_quantized_tensor",
  58. "export_to_pretty_string",
  59. "unconvertible_ops",
  60. "register_custom_op_symbolic",
  61. "unregister_custom_op_symbolic",
  62. ]
  63. def is_in_onnx_export() -> bool:
  64. """Returns whether it is in the middle of ONNX export."""
  65. return GLOBALS.in_onnx_export
  66. # TODO(justinchuby): Remove dependency to this global variable from constant_fold.cpp
  67. # Skip check due to cannot import IValue from torch._C
  68. _params_dict = {} # type: ignore[var-annotated]
  69. @contextlib.contextmanager
  70. @_beartype.beartype
  71. def select_model_mode_for_export(model, mode: _C_onnx.TrainingMode):
  72. r"""A context manager to temporarily set the training mode of ``model``
  73. to ``mode``, resetting it when we exit the with-block.
  74. Args:
  75. model: Same type and meaning as ``model`` arg to :func:`export`.
  76. mode: Same type and meaning as ``training`` arg to :func:`export`.
  77. """
  78. if not isinstance(mode, _C_onnx.TrainingMode):
  79. raise TypeError(
  80. f"'mode' should be a torch.onnx.TrainingMode enum, but got '{type(mode)}'."
  81. )
  82. originally_training: bool = False
  83. if hasattr(model, "training"):
  84. originally_training = model.training
  85. # ONNX opset 12 has better support for training amenable models, with updated
  86. # versions of the dropout and batch_norm operators
  87. if mode == _C_onnx.TrainingMode.TRAINING or (
  88. mode == _C_onnx.TrainingMode.PRESERVE and originally_training
  89. ):
  90. GLOBALS.export_training = True
  91. if GLOBALS.export_onnx_opset_version < 12:
  92. warnings.warn(
  93. "You are exporting the model in training mode with onnx opset "
  94. f"version {GLOBALS.export_onnx_opset_version}. "
  95. "Opset versions lower than opset 12 will not be able to export "
  96. "nodes such as Dropout and BatchNorm correctly."
  97. )
  98. else:
  99. GLOBALS.export_training = False
  100. GLOBALS.training_mode = mode
  101. if mode == _C_onnx.TrainingMode.TRAINING:
  102. model.train(True)
  103. elif mode == _C_onnx.TrainingMode.EVAL:
  104. model.train(False)
  105. # else mode == _C_onnx.TrainingMode.PRESERVE, do nothing
  106. try:
  107. yield
  108. finally:
  109. if hasattr(model, "training") and not mode == _C_onnx.TrainingMode.PRESERVE:
  110. model.train(originally_training)
  111. @contextlib.contextmanager
  112. @_beartype.beartype
  113. def disable_apex_o2_state_dict_hook(
  114. model: Union[torch.nn.Module, torch.jit.ScriptFunction]
  115. ):
  116. # Apex O2 hook state_dict to return fp16 weights as fp32.
  117. # Exporter cannot identify them as same tensors.
  118. # Since this hook is only used by optimizer, it is safe to
  119. # remove this hook while exporting.
  120. if not isinstance(model, torch.jit.ScriptFunction):
  121. model_hooks = {} # type: ignore[var-annotated]
  122. for module in model.modules():
  123. for key, hook in module._state_dict_hooks.items():
  124. if type(hook).__name__ == "O2StateDictHook":
  125. if module not in model_hooks:
  126. model_hooks[module] = {}
  127. model_hooks[module][key] = hook
  128. if module in model_hooks:
  129. for key in model_hooks[module]:
  130. module._state_dict_hooks.pop(key)
  131. try:
  132. yield
  133. finally:
  134. # Add the hooks back
  135. for module, m_map in model_hooks.items():
  136. for key, hook in m_map.items():
  137. module._state_dict_hooks[key] = hook
  138. else:
  139. try:
  140. yield
  141. finally:
  142. pass
  143. @contextlib.contextmanager
  144. @_beartype.beartype
  145. def setup_onnx_logging(verbose: bool):
  146. is_originally_enabled = torch.onnx.is_onnx_log_enabled()
  147. if is_originally_enabled or verbose:
  148. torch.onnx.enable_log()
  149. try:
  150. yield
  151. finally:
  152. if not is_originally_enabled:
  153. torch.onnx.disable_log()
  154. @contextlib.contextmanager
  155. @_beartype.beartype
  156. def exporter_context(model, mode: _C_onnx.TrainingMode, verbose: bool):
  157. with select_model_mode_for_export(
  158. model, mode
  159. ) as mode_ctx, disable_apex_o2_state_dict_hook(
  160. model
  161. ) as apex_ctx, setup_onnx_logging(
  162. verbose
  163. ) as log_ctx, diagnostics.create_export_diagnostic_context() as diagnostic_ctx:
  164. yield (mode_ctx, apex_ctx, log_ctx, diagnostic_ctx)
  165. @_beartype.beartype
  166. def export(
  167. model: Union[torch.nn.Module, torch.jit.ScriptModule, torch.jit.ScriptFunction],
  168. args: Union[Tuple[Any, ...], torch.Tensor],
  169. f: Union[str, io.BytesIO],
  170. export_params: bool = True,
  171. verbose: bool = False,
  172. training: _C_onnx.TrainingMode = _C_onnx.TrainingMode.EVAL,
  173. input_names: Optional[Sequence[str]] = None,
  174. output_names: Optional[Sequence[str]] = None,
  175. operator_export_type: _C_onnx.OperatorExportTypes = _C_onnx.OperatorExportTypes.ONNX,
  176. opset_version: Optional[int] = None,
  177. do_constant_folding: bool = True,
  178. dynamic_axes: Optional[
  179. Union[Mapping[str, Mapping[int, str]], Mapping[str, Sequence[int]]]
  180. ] = None,
  181. keep_initializers_as_inputs: Optional[bool] = None,
  182. custom_opsets: Optional[Mapping[str, int]] = None,
  183. export_modules_as_functions: Union[bool, Collection[Type[torch.nn.Module]]] = False,
  184. ) -> None:
  185. r"""Exports a model into ONNX format.
  186. If ``model`` is not a :class:`torch.jit.ScriptModule` nor a
  187. :class:`torch.jit.ScriptFunction`, this runs
  188. ``model`` once in order to convert it to a TorchScript graph to be exported
  189. (the equivalent of :func:`torch.jit.trace`). Thus this has the same limited support
  190. for dynamic control flow as :func:`torch.jit.trace`.
  191. Args:
  192. model (:class:`torch.nn.Module`, :class:`torch.jit.ScriptModule` or :class:`torch.jit.ScriptFunction`):
  193. the model to be exported.
  194. args (tuple or torch.Tensor):
  195. args can be structured either as:
  196. 1. ONLY A TUPLE OF ARGUMENTS::
  197. args = (x, y, z)
  198. The tuple should contain model inputs such that ``model(*args)`` is a valid
  199. invocation of the model. Any non-Tensor arguments will be hard-coded into the
  200. exported model; any Tensor arguments will become inputs of the exported model,
  201. in the order they occur in the tuple.
  202. 2. A TENSOR::
  203. args = torch.Tensor([1])
  204. This is equivalent to a 1-ary tuple of that Tensor.
  205. 3. A TUPLE OF ARGUMENTS ENDING WITH A DICTIONARY OF NAMED ARGUMENTS::
  206. args = (
  207. x,
  208. {
  209. "y": input_y,
  210. "z": input_z
  211. }
  212. )
  213. All but the last element of the tuple will be passed as non-keyword arguments,
  214. and named arguments will be set from the last element. If a named argument is
  215. not present in the dictionary, it is assigned the default value, or None if a
  216. default value is not provided.
  217. .. note::
  218. If a dictionary is the last element of the args tuple, it will be
  219. interpreted as containing named arguments. In order to pass a dict as the
  220. last non-keyword arg, provide an empty dict as the last element of the args
  221. tuple. For example, instead of::
  222. torch.onnx.export(
  223. model,
  224. (
  225. x,
  226. # WRONG: will be interpreted as named arguments
  227. {y: z}
  228. ),
  229. "test.onnx.pb"
  230. )
  231. Write::
  232. torch.onnx.export(
  233. model,
  234. (
  235. x,
  236. {y: z},
  237. {}
  238. ),
  239. "test.onnx.pb"
  240. )
  241. f: a file-like object (such that ``f.fileno()`` returns a file descriptor)
  242. or a string containing a file name. A binary protocol buffer will be written
  243. to this file.
  244. export_params (bool, default True): if True, all parameters will
  245. be exported. Set this to False if you want to export an untrained model.
  246. In this case, the exported model will first take all of its parameters
  247. as arguments, with the ordering as specified by ``model.state_dict().values()``
  248. verbose (bool, default False): if True, prints a description of the
  249. model being exported to stdout. In addition, the final ONNX graph will include the
  250. field ``doc_string``` from the exported model which mentions the source code locations
  251. for ``model``. If True, ONNX exporter logging will be turned on.
  252. training (enum, default TrainingMode.EVAL):
  253. * ``TrainingMode.EVAL``: export the model in inference mode.
  254. * ``TrainingMode.PRESERVE``: export the model in inference mode if model.training is
  255. False and in training mode if model.training is True.
  256. * ``TrainingMode.TRAINING``: export the model in training mode. Disables optimizations
  257. which might interfere with training.
  258. input_names (list of str, default empty list): names to assign to the
  259. input nodes of the graph, in order.
  260. output_names (list of str, default empty list): names to assign to the
  261. output nodes of the graph, in order.
  262. operator_export_type (enum, default OperatorExportTypes.ONNX):
  263. * ``OperatorExportTypes.ONNX``: Export all ops as regular ONNX ops
  264. (in the default opset domain).
  265. * ``OperatorExportTypes.ONNX_FALLTHROUGH``: Try to convert all ops
  266. to standard ONNX ops in the default opset domain. If unable to do so
  267. (e.g. because support has not been added to convert a particular torch op to ONNX),
  268. fall back to exporting the op into a custom opset domain without conversion. Applies
  269. to `custom ops <https://pytorch.org/tutorials/advanced/torch_script_custom_ops.html>`_
  270. as well as ATen ops. For the exported model to be usable, the runtime must support
  271. these non-standard ops.
  272. * ``OperatorExportTypes.ONNX_ATEN``: All ATen ops (in the TorchScript namespace "aten")
  273. are exported as ATen ops (in opset domain "org.pytorch.aten").
  274. `ATen <https://pytorch.org/cppdocs/#aten>`_ is PyTorch's built-in tensor library, so
  275. this instructs the runtime to use PyTorch's implementation of these ops.
  276. .. warning::
  277. Models exported this way are probably runnable only by Caffe2.
  278. This may be useful if the numeric differences in implementations of operators are
  279. causing large differences in behavior between PyTorch and Caffe2 (which is more
  280. common on untrained models).
  281. * ``OperatorExportTypes.ONNX_ATEN_FALLBACK``: Try to export each ATen op
  282. (in the TorchScript namespace "aten") as a regular ONNX op. If we are unable to do so
  283. (e.g. because support has not been added to convert a particular torch op to ONNX),
  284. fall back to exporting an ATen op. See documentation on OperatorExportTypes.ONNX_ATEN for
  285. context.
  286. For example::
  287. graph(%0 : Float):
  288. %3 : int = prim::Constant[value=0]()
  289. # conversion unsupported
  290. %4 : Float = aten::triu(%0, %3)
  291. # conversion supported
  292. %5 : Float = aten::mul(%4, %0)
  293. return (%5)
  294. Assuming ``aten::triu`` is not supported in ONNX, this will be exported as::
  295. graph(%0 : Float):
  296. %1 : Long() = onnx::Constant[value={0}]()
  297. # not converted
  298. %2 : Float = aten::ATen[operator="triu"](%0, %1)
  299. # converted
  300. %3 : Float = onnx::Mul(%2, %0)
  301. return (%3)
  302. If PyTorch was built with Caffe2 (i.e. with ``BUILD_CAFFE2=1``), then
  303. Caffe2-specific behavior will be enabled, including special support
  304. for ops are produced by the modules described in
  305. `Quantization <https://pytorch.org/docs/stable/quantization.html>`_.
  306. .. warning::
  307. Models exported this way are probably runnable only by Caffe2.
  308. opset_version (int, default 14): The version of the
  309. `default (ai.onnx) opset <https://github.com/onnx/onnx/blob/master/docs/Operators.md>`_
  310. to target. Must be >= 7 and <= 16.
  311. do_constant_folding (bool, default True): Apply the constant-folding optimization.
  312. Constant-folding will replace some of the ops that have all constant inputs
  313. with pre-computed constant nodes.
  314. dynamic_axes (dict[string, dict[int, string]] or dict[string, list(int)], default empty dict):
  315. By default the exported model will have the shapes of all input and output tensors
  316. set to exactly match those given in ``args``. To specify axes of tensors as
  317. dynamic (i.e. known only at run-time), set ``dynamic_axes`` to a dict with schema:
  318. * KEY (str): an input or output name. Each name must also be provided in ``input_names`` or
  319. ``output_names``.
  320. * VALUE (dict or list): If a dict, keys are axis indices and values are axis names. If a
  321. list, each element is an axis index.
  322. For example::
  323. class SumModule(torch.nn.Module):
  324. def forward(self, x):
  325. return torch.sum(x, dim=1)
  326. torch.onnx.export(
  327. SumModule(),
  328. (torch.ones(2, 2),),
  329. "onnx.pb",
  330. input_names=["x"],
  331. output_names=["sum"]
  332. )
  333. Produces::
  334. input {
  335. name: "x"
  336. ...
  337. shape {
  338. dim {
  339. dim_value: 2 # axis 0
  340. }
  341. dim {
  342. dim_value: 2 # axis 1
  343. ...
  344. output {
  345. name: "sum"
  346. ...
  347. shape {
  348. dim {
  349. dim_value: 2 # axis 0
  350. ...
  351. While::
  352. torch.onnx.export(
  353. SumModule(),
  354. (torch.ones(2, 2),),
  355. "onnx.pb",
  356. input_names=["x"],
  357. output_names=["sum"],
  358. dynamic_axes={
  359. # dict value: manually named axes
  360. "x": {0: "my_custom_axis_name"},
  361. # list value: automatic names
  362. "sum": [0],
  363. }
  364. )
  365. Produces::
  366. input {
  367. name: "x"
  368. ...
  369. shape {
  370. dim {
  371. dim_param: "my_custom_axis_name" # axis 0
  372. }
  373. dim {
  374. dim_value: 2 # axis 1
  375. ...
  376. output {
  377. name: "sum"
  378. ...
  379. shape {
  380. dim {
  381. dim_param: "sum_dynamic_axes_1" # axis 0
  382. ...
  383. keep_initializers_as_inputs (bool, default None): If True, all the
  384. initializers (typically corresponding to parameters) in the
  385. exported graph will also be added as inputs to the graph. If False,
  386. then initializers are not added as inputs to the graph, and only
  387. the non-parameter inputs are added as inputs.
  388. This may allow for better optimizations (e.g. constant folding) by
  389. backends/runtimes.
  390. If ``opset_version < 9``, initializers MUST be part of graph
  391. inputs and this argument will be ignored and the behavior will be
  392. equivalent to setting this argument to True.
  393. If None, then the behavior is chosen automatically as follows:
  394. * If ``operator_export_type=OperatorExportTypes.ONNX``, the behavior is equivalent
  395. to setting this argument to False.
  396. * Else, the behavior is equivalent to setting this argument to True.
  397. custom_opsets (dict[str, int], default empty dict): A dict with schema:
  398. * KEY (str): opset domain name
  399. * VALUE (int): opset version
  400. If a custom opset is referenced by ``model`` but not mentioned in this dictionary,
  401. the opset version is set to 1. Only custom opset domain name and version should be
  402. indicated through this argument.
  403. export_modules_as_functions (bool or set of type of nn.Module, default False): Flag to enable
  404. exporting all ``nn.Module`` forward calls as local functions in ONNX. Or a set to indicate the
  405. particular types of modules to export as local functions in ONNX.
  406. This feature requires ``opset_version`` >= 15, otherwise the export will fail. This is because
  407. ``opset_version`` < 15 implies IR version < 8, which means no local function support.
  408. Module variables will be exported as function attributes. There are two categories of function
  409. attributes.
  410. 1. Annotated attributes: class variables that have type annotations via
  411. `PEP 526-style <https://www.python.org/dev/peps/pep-0526/#class-and-instance-variable-annotations>`_
  412. will be exported as attributes.
  413. Annotated attributes are not used inside the subgraph of ONNX local function because
  414. they are not created by PyTorch JIT tracing, but they may be used by consumers
  415. to determine whether or not to replace the function with a particular fused kernel.
  416. 2. Inferred attributes: variables that are used by operators inside the module. Attribute names
  417. will have prefix "inferred::". This is to differentiate from predefined attributes retrieved from
  418. python module annotations. Inferred attributes are used inside the subgraph of ONNX local function.
  419. * ``False`` (default): export ``nn.Module`` forward calls as fine grained nodes.
  420. * ``True``: export all ``nn.Module`` forward calls as local function nodes.
  421. * Set of type of nn.Module: export ``nn.Module`` forward calls as local function nodes,
  422. only if the type of the ``nn.Module`` is found in the set.
  423. Raises:
  424. :class:`torch.onnx.errors.CheckerError`: If the ONNX checker detects an invalid ONNX graph.
  425. :class:`torch.onnx.errors.UnsupportedOperatorError`: If the ONNX graph cannot be exported because it
  426. uses an operator that is not supported by the exporter.
  427. :class:`torch.onnx.errors.OnnxExporterError`: Other errors that can occur during export.
  428. All errors are subclasses of :class:`errors.OnnxExporterError`.
  429. """
  430. _export(
  431. model,
  432. args,
  433. f,
  434. export_params,
  435. verbose,
  436. training,
  437. input_names,
  438. output_names,
  439. operator_export_type=operator_export_type,
  440. opset_version=opset_version,
  441. do_constant_folding=do_constant_folding,
  442. dynamic_axes=dynamic_axes,
  443. keep_initializers_as_inputs=keep_initializers_as_inputs,
  444. custom_opsets=custom_opsets,
  445. export_modules_as_functions=export_modules_as_functions,
  446. )
  447. @_beartype.beartype
  448. def _is_constant_tensor_list(node):
  449. if node.kind() != "prim::Constant":
  450. return False
  451. output_type = node.output().type()
  452. if output_type.isSubtypeOf(_C.ListType.ofTensors()):
  453. return True
  454. if output_type.isSubtypeOf(_C.ListType(_C.OptionalType.ofTensor())):
  455. return True
  456. # ONNX can't handle constants that are lists of tensors, which can
  457. # get generated in constant prop. So we split them back into prim::ListConstructs
  458. @_beartype.beartype
  459. def _split_tensor_list_constants(g, block):
  460. for node in block.nodes():
  461. for subblock in node.blocks():
  462. _split_tensor_list_constants(g, subblock)
  463. if _is_constant_tensor_list(node):
  464. inputs = []
  465. for val in node.output().toIValue():
  466. input = g.insertConstant(val)
  467. input.node().moveBefore(node)
  468. input.node().copyMetadata(node)
  469. inputs.append(input)
  470. lc = (
  471. g.create("prim::ListConstruct", inputs)
  472. .insertBefore(node)
  473. .output()
  474. .setType(_C.ListType.ofTensors())
  475. )
  476. lc.node().copyMetadata(node)
  477. node.output().replaceAllUsesWith(lc)
  478. @_beartype.beartype
  479. def _optimize_graph(
  480. graph: _C.Graph,
  481. operator_export_type: _C_onnx.OperatorExportTypes,
  482. _disable_torch_constant_prop: bool = False,
  483. fixed_batch_size: bool = False,
  484. params_dict=None,
  485. dynamic_axes=None,
  486. input_names=None,
  487. module=None,
  488. ):
  489. if params_dict is None:
  490. params_dict = {}
  491. # Inline everything
  492. _C._jit_pass_inline(graph)
  493. # Remove fork/wait nodes
  494. _C._jit_pass_inline_fork_wait(graph)
  495. _C._jit_pass_lint(graph)
  496. _C._jit_pass_onnx_autograd_function_process(graph)
  497. _C._jit_pass_lower_all_tuples(graph)
  498. # we now record some ops like ones/zeros
  499. # into a trace where we previously recorded constants.
  500. # use constant prop to maintain our current level of onnx support
  501. # without implementing symbolics for all of them
  502. if _disable_torch_constant_prop is False:
  503. _C._jit_pass_constant_propagation(graph)
  504. _split_tensor_list_constants(graph, graph)
  505. # run dce to eliminate dead parts of the graph that might have been
  506. # left behind by things like symbolic_override
  507. _C._jit_pass_dce(graph)
  508. _C._jit_pass_lint(graph)
  509. # CSE should improve perf when Autocast is used with disabled cache
  510. # Autocast is disabled due to a limitation on tracer as described at https://github.com/pytorch/pytorch/issues/84092
  511. # Must run before _C._jit_pass_erase_number_types to prevent type substitution
  512. if _C._jit_pass_cse(graph):
  513. _C._jit_pass_onnx_lint(graph)
  514. _C._jit_pass_canonicalize_graph_fuser_ops(graph)
  515. _C._jit_pass_lint(graph)
  516. _C._jit_pass_peephole(graph, True)
  517. _C._jit_pass_fuse_addmm(graph)
  518. _C._jit_pass_lint(graph)
  519. _C._jit_pass_peephole(graph, True)
  520. _C._jit_pass_lower_all_tuples(graph)
  521. # in _jit_pass_onnx, symbolic functions are called for each node for conversion.
  522. # However, there are nodes that cannot be converted without additional context.
  523. # For example, the number of outputs from split (and whether it is static or dynamic) is unknown
  524. # until the point where it is unpacked by listUnpack node.
  525. # This pass does a preprocess, and prepares the nodes such that enough context can be received
  526. # by the symbolic function.
  527. _C._jit_pass_onnx_remove_inplace_ops_for_onnx(graph, module)
  528. _C._jit_pass_onnx_preprocess(graph)
  529. # onnx does not support tuples, so try to remove them
  530. _C._jit_pass_lint(graph)
  531. # onnx only supports tensors, but 1 / 2 = 0.5 and tensor(1) / tensor(2) = 0
  532. _C._jit_pass_prepare_division_for_onnx(graph)
  533. _C._jit_pass_onnx_remove_print(graph)
  534. _C._jit_pass_onnx_preprocess_caffe2(graph)
  535. symbolic_helper._quantized_ops.clear()
  536. # Unpack quantized weights for conv and linear ops and insert into graph.
  537. _C._jit_pass_onnx_unpack_quantized_weights(
  538. graph, params_dict, symbolic_helper.is_caffe2_aten_fallback()
  539. )
  540. if symbolic_helper.is_caffe2_aten_fallback():
  541. # Insert permutes before and after each conv op to ensure correct order.
  542. _C._jit_pass_onnx_quantization_insert_permutes(graph, params_dict)
  543. # Find consecutive permutes that are no-ops and remove them.
  544. _C._jit_pass_custom_pattern_based_rewrite_graph(
  545. textwrap.dedent(
  546. """\
  547. graph(%Pi):
  548. %Pq = quantized::nhwc2nchw(%Pi)
  549. %Pr = quantized::nchw2nhwc(%Pq)
  550. return (%Pr)"""
  551. ),
  552. textwrap.dedent(
  553. """\
  554. graph(%Ri):
  555. return (%Ri)"""
  556. ),
  557. graph,
  558. )
  559. # onnx only supports tensors, so we turn all out number types into tensors
  560. _C._jit_pass_erase_number_types(graph)
  561. if GLOBALS.onnx_shape_inference:
  562. input_names = [] if input_names is None else input_names
  563. dynamic_axes = {} if dynamic_axes is None else dynamic_axes
  564. _C._jit_pass_onnx_set_dynamic_input_shape(graph, dynamic_axes, input_names)
  565. _C._jit_pass_onnx_lint(graph)
  566. graph = _C._jit_pass_onnx(graph, operator_export_type)
  567. _C._jit_pass_onnx_lint(graph)
  568. _C._jit_pass_lint(graph)
  569. _C._jit_pass_onnx_scalar_type_analysis(
  570. graph, True, GLOBALS.export_onnx_opset_version
  571. )
  572. _C._jit_pass_lint(graph)
  573. _C._jit_pass_onnx_peephole(
  574. graph, GLOBALS.export_onnx_opset_version, fixed_batch_size
  575. )
  576. _C._jit_pass_lint(graph)
  577. # graph is not a valid jit graph anymore because types have been replaced
  578. # (e.g. int with Tensor), so it now contains operators that don't actually
  579. # exist. We can't run normal dead code elimination because it'd fail trying
  580. # to look up if an operator has side effects, but we can run a dead code
  581. # elimination variant that doesn't need to look up if an op has side effects.
  582. _C._jit_pass_dce_allow_deleting_nodes_with_side_effects(graph)
  583. _C._jit_pass_lint(graph)
  584. graph = _C._jit_pass_canonicalize(graph)
  585. _C._jit_pass_lint(graph)
  586. if GLOBALS.onnx_shape_inference:
  587. _C._jit_pass_onnx_graph_shape_type_inference(
  588. graph, params_dict, GLOBALS.export_onnx_opset_version
  589. )
  590. return graph
  591. @_beartype.beartype
  592. def warn_on_static_input_change(input_states):
  593. """Warns that changes to input dictionaries and strings won't take effect in the traced ONNX graph.
  594. We accept dictionaries and strings as ONNX inputs, but they should be only for
  595. configuration use. we detect here if these inputs are modified, and if so we warn
  596. the user that the changes won't take effect in the traced ONNX graph.
  597. """
  598. for input, traced_input in zip(input_states[0], input_states[1]):
  599. if isinstance(input, dict):
  600. if list(input.keys()) != list(traced_input.keys()):
  601. warning = (
  602. "We detected that you are modifying a dictionary that is an input to your "
  603. "model. "
  604. "Note that dictionaries are allowed as inputs in ONNX but they should be "
  605. "handled with care. "
  606. "Usages of dictionaries is not recommended, and should not be used except "
  607. "for configuration use. "
  608. "Also note that the order and values of the keys must remain the same. "
  609. )
  610. warnings.warn(warning)
  611. elif isinstance(input, str):
  612. if input != traced_input:
  613. warning = (
  614. "The model seems to have string inputs/outputs. "
  615. "Note that strings will not appear as inputs/outputs of the ONNX graph. "
  616. )
  617. warnings.warn(warning)
  618. @_beartype.beartype
  619. def _resolve_args_by_export_type(arg_name, arg_value, operator_export_type):
  620. """Resolves the arguments that are ignored when export_type != operator_export_type.ONNX."""
  621. if (
  622. operator_export_type is not operator_export_type.ONNX
  623. and _C_onnx._CAFFE2_ATEN_FALLBACK
  624. ):
  625. if arg_value is True:
  626. warnings.warn(
  627. f"'{arg_name}' can be set to True only when 'operator_export_type' is "
  628. "`ONNX`. Since 'operator_export_type' is not set to 'ONNX', "
  629. f"'{arg_name}' argument will be ignored."
  630. )
  631. arg_value = False
  632. return arg_value
  633. @_beartype.beartype
  634. def _decide_keep_init_as_input(
  635. keep_initializers_as_inputs: Optional[bool],
  636. operator_export_type: _C_onnx.OperatorExportTypes,
  637. opset_version: int,
  638. ):
  639. """Decides whether the initializers in the graph should be listed as ONNX graph inputs.
  640. This method encapsulates the logic to decide whether the initializers in the graph
  641. should be listed as ONNX graph inputs (i.e., whether to choose ONNX IR v3 or v4).
  642. If keep_initializers_as_inputs is not specified (None), then we decide whether to keep
  643. initializers as graph inputs (val_keep_init_as_ip) based on export type. If export type
  644. is ONNX, then do not keep initializers as input (val_keep_init_as_ip=False). For all other
  645. export types keep initializers as input (val_keep_init_as_ip=True).
  646. If keep_initializers_as_inputs is specified, then respect it. Unless opset version <= 8,
  647. in which case it must be ignored because for opset version <= 8, all initializers MUST be
  648. part of graph input (only ONNX IR v3 is allowed), i.e. val_keep_init_as_ip=True.
  649. Special handling is needed for opset version 8 or lower, because irrespective
  650. of user input for keep_initializers_as_inputs, the graph must follow ONNX IR v3
  651. semantics, i.e. all initializers must be listed as ONNX graph input.
  652. """
  653. if opset_version < 9:
  654. if keep_initializers_as_inputs is False:
  655. warnings.warn(
  656. "Setting 'keep_initializers_as_inputs=False' for opset version"
  657. "8 or lower would lead to an invalid ONNX graph. Therefore, "
  658. "'keep_initializers_as_inputs=False' is ignored during export."
  659. "Exported model will have initializers as graph inputs (compliant "
  660. " to ONNX IR v3)."
  661. )
  662. return True # i.e. True == initializers are part of graph input (ONNX IR v3)
  663. val_keep_init_as_ip = (
  664. True if keep_initializers_as_inputs is None else keep_initializers_as_inputs
  665. )
  666. if (
  667. keep_initializers_as_inputs is None
  668. and operator_export_type is _C_onnx.OperatorExportTypes.ONNX
  669. ):
  670. val_keep_init_as_ip = False
  671. return val_keep_init_as_ip
  672. @_beartype.beartype
  673. def _decide_add_node_names(add_node_names, operator_export_type):
  674. return _resolve_args_by_export_type(
  675. "add_node_names", add_node_names, operator_export_type
  676. )
  677. @_beartype.beartype
  678. def _decide_constant_folding(do_constant_folding, operator_export_type, training):
  679. do_constant_folding = _resolve_args_by_export_type(
  680. "do_constant_folding", do_constant_folding, operator_export_type
  681. )
  682. if do_constant_folding and (
  683. training is not None and training is not _C_onnx.TrainingMode.EVAL
  684. ):
  685. warnings.warn(
  686. "It is recommended that constant folding be turned off ('do_constant_folding=False') "
  687. "when exporting the model in training-amenable mode, i.e. with 'training=TrainingMode.TRAIN' "
  688. "or 'training=TrainingMode.PRESERVE' (when model is in training mode). Otherwise, some "
  689. "learnable model parameters may not translate correctly in the exported ONNX model "
  690. "because constant folding mutates model parameters. Please consider "
  691. "turning off constant folding or setting the training=TrainingMode.EVAL."
  692. )
  693. return do_constant_folding
  694. @_beartype.beartype
  695. def _signature(model) -> inspect.Signature:
  696. should_be_callable = getattr(model, "forward", model)
  697. if callable(should_be_callable):
  698. return inspect.signature(should_be_callable)
  699. raise ValueError("model has no forward method and is not callable")
  700. @_beartype.beartype
  701. def _decide_input_format(model, args):
  702. try:
  703. sig = _signature(model)
  704. except ValueError as e:
  705. warnings.warn(f"{e}, skipping _decide_input_format")
  706. return args
  707. try:
  708. ordered_list_keys = list(sig.parameters.keys())
  709. if ordered_list_keys[0] == "self":
  710. ordered_list_keys = ordered_list_keys[1:]
  711. args_dict: Dict = {}
  712. if isinstance(args, list):
  713. args_list = args
  714. elif isinstance(args, tuple):
  715. args_list = list(args)
  716. else:
  717. args_list = [args]
  718. if isinstance(args_list[-1], dict):
  719. args_dict = args_list[-1]
  720. args_list = args_list[:-1]
  721. n_nonkeyword = len(args_list)
  722. for optional_arg in ordered_list_keys[n_nonkeyword:]:
  723. if optional_arg in args_dict:
  724. args_list.append(args_dict[optional_arg])
  725. # Check if this arg has a default value
  726. else:
  727. param = sig.parameters[optional_arg]
  728. if param.default != param.empty:
  729. args_list.append(param.default)
  730. args = args_list if isinstance(args, list) else tuple(args_list)
  731. # Cases of models with no input args
  732. except IndexError:
  733. warnings.warn("No input args, skipping _decide_input_format")
  734. except Exception as e:
  735. warnings.warn(f"Skipping _decide_input_format\n {e.args[0]}")
  736. return args
  737. @_beartype.beartype
  738. def _trace(func, args, operator_export_type, return_outs=False):
  739. # Special case for common case of passing a single Tensor
  740. if isinstance(args, torch.Tensor):
  741. args = (args,)
  742. trace_graph, torch_out, inputs_states = torch.jit._get_trace_graph(
  743. func,
  744. args,
  745. strict=False,
  746. _force_outplace=False,
  747. _return_inputs_states=True,
  748. )
  749. warn_on_static_input_change(inputs_states)
  750. trace_graph = _optimize_graph(trace_graph, operator_export_type, params_dict={})
  751. if return_outs:
  752. return trace_graph, torch_out
  753. return trace_graph
  754. @_beartype.beartype
  755. def _trace_and_get_graph_from_model(model, args):
  756. # A basic sanity check: make sure the state_dict keys are the same
  757. # before and after running the model. Fail fast!
  758. orig_state_dict_keys = torch.jit._unique_state_dict(model).keys()
  759. # Disable Autocast cache because it replaces kernel's weight and bias
  760. # by (undesired) constants.
  761. # No perf impact for when there are reused weights since https://github.com/pytorch/pytorch/pull/85665
  762. # TODO: https://github.com/pytorch/pytorch/issues/84092
  763. prev_autocast_cache_enabled = torch.is_autocast_cache_enabled()
  764. torch.set_autocast_cache_enabled(False)
  765. trace_graph, torch_out, inputs_states = torch.jit._get_trace_graph(
  766. model,
  767. args,
  768. strict=False,
  769. _force_outplace=False,
  770. _return_inputs_states=True,
  771. )
  772. torch.set_autocast_cache_enabled(prev_autocast_cache_enabled)
  773. warn_on_static_input_change(inputs_states)
  774. if orig_state_dict_keys != torch.jit._unique_state_dict(model).keys():
  775. raise RuntimeError(
  776. "state_dict changed after running the tracer; "
  777. "something weird is happening in your model!"
  778. )
  779. return trace_graph, torch_out
  780. @_beartype.beartype
  781. def _get_param_count_list(method_graph, args_params):
  782. param_count_list = []
  783. for input_, arg_params_ in zip(method_graph.inputs(), args_params):
  784. if "PackedParams" in str(input_.type()):
  785. in_vars, _ = torch.jit._flatten(arg_params_)
  786. param_count_list.append(len(in_vars))
  787. else:
  788. param_count_list.append(arg_params_ is not None)
  789. return param_count_list
  790. @_beartype.beartype
  791. def _check_flatten_did_not_remove(original, jit_flattened):
  792. """torch.jit._flatten removes None. Check if it did so in this case."""
  793. @_beartype.beartype
  794. def flatten(x):
  795. if isinstance(x, (list, tuple)):
  796. for inner in x:
  797. yield from flatten(inner)
  798. elif isinstance(x, dict):
  799. for inner in x.values():
  800. yield from flatten(inner)
  801. else:
  802. yield x
  803. flattened_with_none = list(flatten(original))
  804. num_none = len(flattened_with_none) - len(jit_flattened)
  805. assert num_none >= 0
  806. if num_none:
  807. raise ValueError(
  808. f"args contained {num_none} None's after flattening. "
  809. "When exporting a ScriptModule or ScriptFunction, no args may "
  810. "be None because that breaks type propagation."
  811. )
  812. def _create_jit_graph(
  813. model: Union[torch.nn.Module, torch.jit.ScriptFunction], args: Sequence[Any]
  814. ) -> Tuple[_C.Graph, List[_C.IValue], Optional[Any], Optional[_C.ScriptModule]]:
  815. if isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule)):
  816. flattened_args = tuple(torch.jit._flatten(tuple(args))[0])
  817. _check_flatten_did_not_remove(args, flattened_args)
  818. torch_out = None
  819. if isinstance(model, torch.jit.ScriptModule):
  820. try:
  821. graph = model.forward.graph # type: ignore[attr-defined]
  822. except AttributeError as e:
  823. raise RuntimeError("'forward' method must be a script method") from e
  824. _C._jit_pass_onnx_function_substitution(graph)
  825. freezed_module = _C._freeze_module(
  826. cast(_C.ScriptModule, model._c), preserveParameters=True
  827. )
  828. module, params = _C._jit_onnx_list_model_parameters(freezed_module)
  829. method_graph = module._get_method("forward").graph
  830. args_params = tuple(args) + tuple(params)
  831. param_count_list = _get_param_count_list(method_graph, args_params)
  832. in_vars, _ = torch.jit._flatten(args_params)
  833. graph = _C._propagate_and_assign_input_shapes(
  834. method_graph, tuple(in_vars), param_count_list, False, False
  835. )
  836. return graph, params, torch_out, module
  837. # torch.jit.ScriptFunction
  838. params = []
  839. graph = model.graph
  840. _C._jit_pass_onnx_function_substitution(graph)
  841. param_count_list = _get_param_count_list(graph, args)
  842. graph = _C._propagate_and_assign_input_shapes(
  843. graph, flattened_args, param_count_list, False, False
  844. )
  845. return graph, params, torch_out, None
  846. graph, torch_out = _trace_and_get_graph_from_model(model, args)
  847. _C._jit_pass_onnx_lint(graph)
  848. state_dict = torch.jit._unique_state_dict(model)
  849. params = list(state_dict.values())
  850. graph_inputs = list(graph.inputs())
  851. user_input_num = len(graph_inputs) - len(state_dict)
  852. param_names = list(state_dict.keys())
  853. for i, inp in enumerate(graph_inputs):
  854. if i >= user_input_num:
  855. inp.setDebugName(param_names[i - user_input_num])
  856. _C._jit_pass_onnx_function_substitution(graph)
  857. return graph, params, torch_out, None
  858. @_beartype.beartype
  859. def _get_named_param_dict(graph, params):
  860. input_and_param_names = [val.debugName() for val in graph.inputs()]
  861. param_names = input_and_param_names[len(input_and_param_names) - len(params) :]
  862. _params_dict = dict(zip(param_names, params))
  863. return _params_dict
  864. @_beartype.beartype
  865. def _get_example_outputs(model, args):
  866. input_args = copy.deepcopy(args)
  867. input_kwargs = {}
  868. if input_args and isinstance(input_args[-1], dict):
  869. input_kwargs = input_args[-1]
  870. input_args = input_args[:-1]
  871. example_outputs = model(*input_args, **input_kwargs)
  872. if isinstance(example_outputs, list):
  873. example_outputs = [example_outputs]
  874. elif not isinstance(example_outputs, tuple):
  875. example_outputs = (example_outputs,)
  876. return example_outputs
  877. _qtype_vtype_map = {
  878. torch.quint8: torch.uint8,
  879. torch.qint8: torch.int8,
  880. torch.qint32: torch.int32,
  881. torch.quint4x2: torch.int8,
  882. }
  883. @_beartype.beartype
  884. def unpack_quantized_tensor(value, cast_onnx_accepted=True):
  885. if isinstance(value, torch.Tensor) and value.dtype in _qtype_vtype_map:
  886. q_value_dequantize = value.dequantize()
  887. q_scale = (
  888. torch.tensor(value.q_scale(), dtype=torch.double)
  889. if cast_onnx_accepted
  890. else torch.tensor(value.q_scale(), dtype=torch.float32)
  891. )
  892. q_zero_point = (
  893. torch.tensor(value.q_zero_point(), dtype=torch.int64)
  894. if cast_onnx_accepted
  895. else torch.tensor(value.q_zero_point(), dtype=_qtype_vtype_map[value.dtype])
  896. )
  897. q_value = q_value_dequantize / q_scale + q_zero_point
  898. q_value = q_value.to(dtype=_qtype_vtype_map[value.dtype])
  899. return q_value, q_scale, q_zero_point
  900. else:
  901. return (value,)
  902. @_beartype.beartype
  903. def _pre_trace_quant_model(model, args):
  904. r"""Returns `torch.jit.trace(model, args)` if model is quantized. Otherwise do nothing and return
  905. original model.
  906. This is due to https://github.com/pytorch/pytorch/issues/75761.
  907. """
  908. if any(
  909. hasattr(m, "_packed_params") for m in getattr(model, "modules", list)()
  910. ) or any(getattr(arg, "is_quantized", False) for arg in args):
  911. return torch.jit.trace(model, args)
  912. return model
  913. @_beartype.beartype
  914. def _model_to_graph(
  915. model,
  916. args,
  917. verbose=False,
  918. input_names=None,
  919. output_names=None,
  920. operator_export_type=_C_onnx.OperatorExportTypes.ONNX,
  921. do_constant_folding=True,
  922. _disable_torch_constant_prop=False,
  923. fixed_batch_size=False,
  924. training=_C_onnx.TrainingMode.EVAL,
  925. dynamic_axes=None,
  926. ) -> Tuple[
  927. _C.Graph,
  928. Dict[str, torch.Tensor],
  929. Optional[
  930. Union[
  931. torch.Tensor,
  932. Tuple[torch.Tensor, ...],
  933. List[torch.Tensor],
  934. Dict[str, torch.Tensor],
  935. Any, # Can be nested tuples etc.
  936. ]
  937. ],
  938. ]:
  939. """Converts model into an ONNX graph.
  940. Returns:
  941. graph: A TorchScript IR Graph with ONNX nodes.
  942. params_dict: Dict from input param name to param value.
  943. torch_out: The output tensors resulting from the trace of ``model``.
  944. If ``model`` is a :class:`torch.jit.ScriptModule` or :class:`torch.jit.ScriptFunction`,
  945. this will be None, since we are not doing any tracing.
  946. """
  947. # TODO: can we simplify this to always return a tuple of Tensor or None?
  948. # Special case for common case of passing a single Tensor
  949. if isinstance(args, (torch.Tensor, int, float, bool)):
  950. args = (args,)
  951. model = _pre_trace_quant_model(model, args)
  952. graph, params, torch_out, module = _create_jit_graph(model, args)
  953. params_dict = _get_named_param_dict(graph, params)
  954. try:
  955. graph = _optimize_graph(
  956. graph,
  957. operator_export_type,
  958. _disable_torch_constant_prop=_disable_torch_constant_prop,
  959. fixed_batch_size=fixed_batch_size,
  960. params_dict=params_dict,
  961. dynamic_axes=dynamic_axes,
  962. input_names=input_names,
  963. module=module,
  964. )
  965. except Exception as e:
  966. torch.onnx.log("Torch IR graph at exception: ", graph)
  967. raise
  968. is_script = isinstance(model, (torch.jit.ScriptFunction, torch.jit.ScriptModule))
  969. if is_script:
  970. example_outputs = _get_example_outputs(model, args)
  971. example_outputs_final = ()
  972. for example_output in example_outputs:
  973. example_outputs_final += unpack_quantized_tensor(example_output)
  974. out_vars, desc = torch.jit._flatten(example_outputs_final)
  975. _C._jit_pass_onnx_assign_output_shape(
  976. graph,
  977. out_vars,
  978. desc,
  979. GLOBALS.onnx_shape_inference,
  980. is_script,
  981. GLOBALS.export_onnx_opset_version,
  982. )
  983. # NB: ONNX requires complete information about output types, which might be
  984. # erased by some optimizations, so we need to set it explicitly again.
  985. else:
  986. if not isinstance(torch_out, (list, tuple)):
  987. output_wrapped = [torch_out]
  988. else:
  989. output_wrapped = torch_out # type: ignore[assignment]
  990. output_tensors, out_desc = torch.jit._flatten(tuple(output_wrapped))
  991. # assign_output_shape pass is not compatible with quantized outputs.
  992. # Quantized outputs are flattened to 3 values in ONNX, while packed as
  993. # single value in PyTorch.
  994. if not any(getattr(out, "is_quantized", False) for out in output_tensors):
  995. _C._jit_pass_onnx_assign_output_shape(
  996. graph,
  997. output_tensors,
  998. out_desc,
  999. GLOBALS.onnx_shape_inference,
  1000. is_script,
  1001. GLOBALS.export_onnx_opset_version,
  1002. )
  1003. _set_input_and_output_names(graph, input_names, output_names)
  1004. params_dict = _get_named_param_dict(graph, params)
  1005. if training is None or training == _C_onnx.TrainingMode.EVAL:
  1006. params_dict = _C._jit_pass_onnx_eval_peephole(graph, params_dict)
  1007. if (
  1008. do_constant_folding
  1009. and GLOBALS.export_onnx_opset_version
  1010. >= _constants.ONNX_CONSTANT_FOLDING_MIN_OPSET
  1011. ):
  1012. params_dict = _C._jit_pass_onnx_constant_fold(
  1013. graph, params_dict, GLOBALS.export_onnx_opset_version
  1014. )
  1015. _C._jit_pass_dce_allow_deleting_nodes_with_side_effects(graph)
  1016. if GLOBALS.onnx_shape_inference:
  1017. _C._jit_pass_onnx_graph_shape_type_inference(
  1018. graph, params_dict, GLOBALS.export_onnx_opset_version
  1019. )
  1020. params_dict = _C._jit_pass_onnx_eliminate_unused_items(graph, params_dict)
  1021. # For ONNX opset < 9, constants only have three data types: float16, float, double.
  1022. # In this pass transform constants of other data types to float/double + cast operator.
  1023. if GLOBALS.export_onnx_opset_version < 9:
  1024. _C._jit_pass_onnx_cast_all_constant_to_floating(graph)
  1025. params_dict = _C._jit_pass_filter_non_tensor_arguments(params_dict)
  1026. _C._jit_decay_packed_param_input_types(graph)
  1027. # If output names lack a proper name and are identified only by their unique
  1028. # give them a legible name for debugging purposes
  1029. _apply_friendly_debug_names(graph, params_dict)
  1030. return graph, params_dict, torch_out
  1031. @_beartype.beartype
  1032. def export_to_pretty_string(
  1033. model,
  1034. args,
  1035. export_params=True,
  1036. verbose=False,
  1037. training=_C_onnx.TrainingMode.EVAL,
  1038. input_names=None,
  1039. output_names=None,
  1040. operator_export_type=_C_onnx.OperatorExportTypes.ONNX,
  1041. export_type=None,
  1042. google_printer=False,
  1043. opset_version=None,
  1044. keep_initializers_as_inputs=None,
  1045. custom_opsets=None,
  1046. add_node_names=True,
  1047. do_constant_folding=True,
  1048. dynamic_axes=None,
  1049. ):
  1050. r"""
  1051. Similar to :func:`export`, but returns a text representation of the ONNX
  1052. model. Only differences in args listed below. All other args are the same
  1053. as :func:`export`.
  1054. Args:
  1055. add_node_names (bool, default True): Whether or not to set
  1056. NodeProto.name. This makes no difference unless
  1057. ``google_printer=True``.
  1058. google_printer (bool, default False): If False, will return a custom,
  1059. compact representation of the model. If True will return the
  1060. protobuf's `Message::DebugString()`, which is more verbose.
  1061. Returns:
  1062. A UTF-8 str containing a human-readable representation of the ONNX model.
  1063. """
  1064. if opset_version is None:
  1065. opset_version = _constants.ONNX_DEFAULT_OPSET
  1066. if custom_opsets is None:
  1067. custom_opsets = {}
  1068. GLOBALS.export_onnx_opset_version = opset_version
  1069. GLOBALS.operator_export_type = operator_export_type
  1070. with exporter_context(model, training, verbose):
  1071. val_keep_init_as_ip = _decide_keep_init_as_input(
  1072. keep_initializers_as_inputs, operator_export_type, opset_version
  1073. )
  1074. val_add_node_names = _decide_add_node_names(
  1075. add_node_names, operator_export_type
  1076. )
  1077. val_do_constant_folding = _decide_constant_folding(
  1078. do_constant_folding, operator_export_type, training
  1079. )
  1080. args = _decide_input_format(model, args)
  1081. graph, params_dict, torch_out = _model_to_graph(
  1082. model,
  1083. args,
  1084. verbose,
  1085. input_names,
  1086. output_names,
  1087. operator_export_type,
  1088. val_do_constant_folding,
  1089. training=training,
  1090. dynamic_axes=dynamic_axes,
  1091. )
  1092. return graph._pretty_print_onnx( # type: ignore[attr-defined]
  1093. params_dict,
  1094. opset_version,
  1095. False,
  1096. operator_export_type,
  1097. google_printer,
  1098. val_keep_init_as_ip,
  1099. custom_opsets,
  1100. val_add_node_names,
  1101. )
  1102. @_beartype.beartype
  1103. def unconvertible_ops(
  1104. model,
  1105. args,
  1106. training: _C_onnx.TrainingMode = _C_onnx.TrainingMode.EVAL,
  1107. opset_version: Optional[int] = None,
  1108. ) -> Tuple[_C.Graph, List[str]]:
  1109. """Returns an approximated list of all ops that are yet supported by :mod:`torch.onnx`.
  1110. The list is approximated because some ops may be removed during the conversion
  1111. process and don't need to be converted. Some other ops may have partial support
  1112. that will fail conversion with particular inputs. Please open a Github Issue
  1113. for op support requests.
  1114. Args:
  1115. model: Same as the `model` parameter in :func:`torch.onnx.export`.
  1116. args: Same as the `args` parameter in :func:`torch.onnx.export`.
  1117. training: Same as the `training` parameter in :func:`torch.onnx.export`.
  1118. opset_version: Same as the `opset_version` parameter in :func:`torch.onnx.export`.
  1119. Returns:
  1120. The JIT graph and a list of unconvertible ops in the format of "domain::op".
  1121. """
  1122. opset_version = opset_version or _constants.ONNX_DEFAULT_OPSET
  1123. GLOBALS.export_onnx_opset_version = opset_version
  1124. try:
  1125. with exporter_context(model, training, verbose=False):
  1126. # Create a mostly clean JIT graph that contains the plain aten and
  1127. # other ops we can check with the symbolic registry.
  1128. # NOTE: We don't want to actually convert any ops to ONNX or run any
  1129. # symbolic functions because there is a higher chance that a pass
  1130. # fails or an unconvertible op messes up the graph during ONNX conversion.
  1131. # This way we can always generate a list just by looking at the names
  1132. # of the ops in the graph.
  1133. args = _decide_input_format(model, args)
  1134. model = _pre_trace_quant_model(model, args)
  1135. graph, _, _, module = _create_jit_graph(model, args)
  1136. _C._jit_pass_inline(graph)
  1137. _C._jit_pass_onnx_remove_inplace_ops_for_onnx(graph, module)
  1138. _C._jit_pass_erase_number_types(graph)
  1139. _C._jit_pass_dce_allow_deleting_nodes_with_side_effects(graph)
  1140. except Exception as e:
  1141. raise errors.OnnxExporterError(
  1142. "Failed to discover unconvertible ops because of errors during the JIT graph "
  1143. "generation process."
  1144. ) from e
  1145. unsupported_ops = []
  1146. for node in graph.nodes():
  1147. domain_op = node.kind()
  1148. if domain_op.startswith("onnx::") or domain_op.startswith("prim::"):
  1149. # We consider onnx and prim ops as supported ops, even though some "prim"
  1150. # ops are not implemented as symbolic functions, because they may be
  1151. # eliminated in the conversion passes. Users may still see errors caused
  1152. # by prim ops even though they don't show up in the list.
  1153. continue
  1154. if not registration.registry.is_registered_op(
  1155. domain_op.rstrip("_"), opset_version
  1156. ):
  1157. # We consider all registered ops supported, even though some of them are
  1158. # only partially supported, because there is not yet a good way to check
  1159. # if an op is fully supported.
  1160. # TODO(justinchuby): Create a way to check if an op is fully supported.
  1161. unsupported_ops.append(domain_op)
  1162. return graph, unsupported_ops
  1163. @_beartype.beartype
  1164. def _setup_trace_module_map(
  1165. model: Union[torch.nn.Module, torch.jit.ScriptModule],
  1166. export_modules_as_functions: Union[bool, Collection[Type[torch.nn.Module]]],
  1167. ) -> Set[str]:
  1168. def __register_attribute_hook():
  1169. attr_name = "_onnx_attrs"
  1170. def _track_module_attributes_forward_pre_hook(module, input):
  1171. setattr(module, attr_name, _get_module_attributes(module))
  1172. def _track_module_attributes_forward_hook(module, input, output):
  1173. tracing_state = _C._get_tracing_state()
  1174. if not tracing_state:
  1175. return
  1176. graph = tracing_state.graph()
  1177. onnx_attrs = {}
  1178. if hasattr(module, attr_name):
  1179. onnx_attrs = getattr(module, attr_name)
  1180. delattr(module, attr_name)
  1181. _C._jit_pass_onnx_track_scope_attributes(graph, onnx_attrs)
  1182. for m in model.modules():
  1183. m.register_forward_hook(_track_module_attributes_forward_hook)
  1184. m.register_forward_pre_hook(_track_module_attributes_forward_pre_hook)
  1185. def _unqualified_variable_name(qualified_name: str) -> str:
  1186. """
  1187. Parse qualified variable name and return the unqualified version.
  1188. Pure numeric atoms are considered inadequate, so this function will look past them,
  1189. and start from the first non-numeric atom.
  1190. Example:
  1191. >>> _unqualified_variable_name('__main__.Foo.bar')
  1192. 'bar'
  1193. >>> _unqualified_variable_name('__main__.Foo.bar.0')
  1194. 'bar.0'
  1195. """
  1196. name_atoms = qualified_name.split(".")
  1197. for i, atom in reversed(list(enumerate(name_atoms))):
  1198. if not atom.isnumeric():
  1199. return ".".join(name_atoms[i:])
  1200. return qualified_name
  1201. trace_module_map = {
  1202. _m: torch._C._jit_onnx_create_full_scope_name(
  1203. torch.typename(type(_m)), _unqualified_variable_name(_n)
  1204. )
  1205. for _n, _m in model.named_modules()
  1206. }
  1207. torch.jit._trace._trace_module_map = trace_module_map
  1208. if isinstance(export_modules_as_functions, bool) and export_modules_as_functions:
  1209. module_typenames = {torch.typename(type(module)) for module in trace_module_map}
  1210. elif isinstance(export_modules_as_functions, set) and export_modules_as_functions:
  1211. def _find_typename(v):
  1212. if isinstance(v, type):
  1213. return torch.typename(v)
  1214. else:
  1215. raise RuntimeError(
  1216. "Only type of the `nn.Module` should be "
  1217. "passed in the set for argument `export_modules_as_functions`. "
  1218. "Got `%s`." % (type(v).__name__)
  1219. )
  1220. module_typenames = {_find_typename(v) for v in export_modules_as_functions}
  1221. else:
  1222. module_typenames = set()
  1223. if module_typenames:
  1224. __register_attribute_hook()
  1225. return module_typenames
  1226. @_beartype.beartype
  1227. def _reset_trace_module_map():
  1228. torch.jit._trace._trace_module_map = None
  1229. _C._jit_pass_onnx_clear_scope_records()
  1230. @_beartype.beartype
  1231. def _get_module_attributes(module):
  1232. annotations = typing.get_type_hints(type(module))
  1233. base_m_annotations = typing.get_type_hints(torch.nn.Module)
  1234. [annotations.pop(k, None) for k in base_m_annotations]
  1235. return {k: getattr(module, k) for k in annotations}
  1236. @_beartype.beartype
  1237. def _export(
  1238. model,
  1239. args,
  1240. f,
  1241. export_params=True,
  1242. verbose=False,
  1243. training=_C_onnx.TrainingMode.EVAL,
  1244. input_names=None,
  1245. output_names=None,
  1246. operator_export_type=_C_onnx.OperatorExportTypes.ONNX,
  1247. export_type=None,
  1248. opset_version=None,
  1249. do_constant_folding=True,
  1250. dynamic_axes=None,
  1251. keep_initializers_as_inputs=None,
  1252. fixed_batch_size=False,
  1253. custom_opsets=None,
  1254. add_node_names=True,
  1255. onnx_shape_inference=True,
  1256. export_modules_as_functions=False,
  1257. ):
  1258. assert GLOBALS.in_onnx_export is False
  1259. if export_type is None:
  1260. export_type = _exporter_states.ExportTypes.PROTOBUF_FILE
  1261. # Discussed deprecation with Nikita Shulga and Sergii Dymchenko from Meta
  1262. if _C_onnx._CAFFE2_ATEN_FALLBACK:
  1263. warnings.warn(
  1264. "Caffe2 ONNX exporter is deprecated in version 2.0 and will be "
  1265. "removed in 2.2. Please use PyTorch 2.1 or older for this capability.",
  1266. category=FutureWarning,
  1267. stacklevel=2,
  1268. )
  1269. if isinstance(model, torch.nn.DataParallel):
  1270. raise ValueError(
  1271. "torch.nn.DataParallel is not supported by ONNX "
  1272. "exporter, please use 'attribute' module to "
  1273. "unwrap model from torch.nn.DataParallel. Try "
  1274. "torch.onnx.export(model.module, ...)"
  1275. )
  1276. GLOBALS.onnx_shape_inference = onnx_shape_inference
  1277. if opset_version is None:
  1278. opset_version = _constants.ONNX_DEFAULT_OPSET
  1279. if export_modules_as_functions and opset_version < 15:
  1280. raise ValueError(
  1281. "`export_modules_as_functions` is not supported for `opset_version` < 15."
  1282. "This is because `opset_version` < 15 implies IR version < 8, which means "
  1283. "no local function support. "
  1284. )
  1285. if not operator_export_type:
  1286. if _C_onnx._CAFFE2_ATEN_FALLBACK:
  1287. operator_export_type = _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK
  1288. else:
  1289. operator_export_type = _C_onnx.OperatorExportTypes.ONNX
  1290. # By default, training=TrainingMode.EVAL,
  1291. # which is good because running a model in training mode could result in
  1292. # internal buffers getting updated, dropout getting applied, etc.
  1293. # If you really know what you're doing, you can turn
  1294. # training=TrainingMode.TRAINING or training=TrainingMode.PRESERVE,
  1295. # (to preserve whatever the original training mode was.)
  1296. GLOBALS.export_onnx_opset_version = opset_version
  1297. GLOBALS.operator_export_type = operator_export_type
  1298. try:
  1299. GLOBALS.in_onnx_export = True
  1300. module_typenames_to_export_as_functions: Set[str] = set()
  1301. if isinstance(model, (torch.nn.Module, torch.jit.ScriptModule)):
  1302. module_typenames_to_export_as_functions = _setup_trace_module_map(
  1303. model, export_modules_as_functions
  1304. )
  1305. with exporter_context(model, training, verbose):
  1306. val_keep_init_as_ip = _decide_keep_init_as_input(
  1307. keep_initializers_as_inputs,
  1308. operator_export_type,
  1309. opset_version,
  1310. )
  1311. val_add_node_names = _decide_add_node_names(
  1312. add_node_names, operator_export_type
  1313. )
  1314. val_do_constant_folding = _decide_constant_folding(
  1315. do_constant_folding, operator_export_type, training
  1316. )
  1317. # Normally f can be a file-like object, but for large models, the external data format requires a
  1318. # valid `model_file_location`. Code in export.cpp will enforce this.
  1319. if isinstance(f, str):
  1320. model_file_location = f
  1321. else:
  1322. model_file_location = ""
  1323. args = _decide_input_format(model, args)
  1324. if dynamic_axes is None:
  1325. dynamic_axes = {}
  1326. _validate_dynamic_axes(dynamic_axes, model, input_names, output_names)
  1327. graph, params_dict, torch_out = _model_to_graph(
  1328. model,
  1329. args,
  1330. verbose,
  1331. input_names,
  1332. output_names,
  1333. operator_export_type,
  1334. val_do_constant_folding,
  1335. fixed_batch_size=fixed_batch_size,
  1336. training=training,
  1337. dynamic_axes=dynamic_axes,
  1338. )
  1339. # TODO: Don't allocate a in-memory string for the protobuf
  1340. defer_weight_export = (
  1341. export_type is not _exporter_states.ExportTypes.PROTOBUF_FILE
  1342. )
  1343. if custom_opsets is None:
  1344. custom_opsets = {}
  1345. _C._jit_pass_dce_allow_deleting_nodes_with_side_effects(graph)
  1346. node_attr_to_name = {} # type: ignore[var-annotated]
  1347. if module_typenames_to_export_as_functions:
  1348. # NOTE: cannot call DCE after this pass. DCE will remove function definition nodes.
  1349. node_attr_to_name = _C._jit_pass_onnx_function_extraction(
  1350. graph,
  1351. module_typenames_to_export_as_functions,
  1352. list(params_dict.keys()),
  1353. )
  1354. params_dict = _C._jit_pass_onnx_deduplicate_initializers( # type: ignore[assignment]
  1355. graph, params_dict, getattr(model, "training", False) # type: ignore[arg-type]
  1356. )
  1357. _C._jit_pass_onnx_assign_scoped_names_for_node_and_value(graph)
  1358. if export_params:
  1359. (
  1360. proto,
  1361. export_map,
  1362. val_use_external_data_format,
  1363. node_names,
  1364. ) = graph._export_onnx( # type: ignore[attr-defined]
  1365. params_dict,
  1366. opset_version,
  1367. dynamic_axes,
  1368. defer_weight_export,
  1369. operator_export_type,
  1370. not verbose,
  1371. val_keep_init_as_ip,
  1372. custom_opsets,
  1373. val_add_node_names,
  1374. model_file_location,
  1375. node_attr_to_name,
  1376. )
  1377. else:
  1378. (
  1379. proto,
  1380. export_map,
  1381. val_use_external_data_format,
  1382. node_names,
  1383. ) = graph._export_onnx( # type: ignore[attr-defined]
  1384. {},
  1385. opset_version,
  1386. dynamic_axes,
  1387. False,
  1388. operator_export_type,
  1389. not verbose,
  1390. val_keep_init_as_ip,
  1391. custom_opsets,
  1392. val_add_node_names,
  1393. model_file_location,
  1394. node_attr_to_name,
  1395. )
  1396. # insert function_proto into model_proto.
  1397. proto = onnx_proto_utils._add_onnxscript_fn(
  1398. proto,
  1399. custom_opsets,
  1400. )
  1401. if verbose:
  1402. torch.onnx.log("Exported graph: ", graph)
  1403. onnx_proto_utils._export_file(proto, f, export_type, export_map)
  1404. # The ONNX checker only works for ONNX graph. So if the operator_export_type is not ONNX,
  1405. # we can skip this check.
  1406. # If large model format export is enabled, proto will only contain data location instead of
  1407. # raw data and _check_onnx_proto() will fail because it can only handle the raw ONNX proto
  1408. # string in memory.
  1409. if (operator_export_type is _C_onnx.OperatorExportTypes.ONNX) and (
  1410. not val_use_external_data_format
  1411. ):
  1412. try:
  1413. _C._check_onnx_proto(proto)
  1414. except RuntimeError as e:
  1415. raise errors.CheckerError(e) from e
  1416. finally:
  1417. assert GLOBALS.in_onnx_export
  1418. GLOBALS.in_onnx_export = False
  1419. _reset_trace_module_map()
  1420. return torch_out
  1421. @_beartype.beartype
  1422. def _apply_friendly_debug_names(graph, params):
  1423. for n in graph.nodes():
  1424. for v in n.inputs():
  1425. old_name = v.debugName()
  1426. if old_name != str(v.unique()):
  1427. continue
  1428. new_name = f"{n.kind()}_{v.unique()}"
  1429. v.setDebugName(new_name)
  1430. if old_name in params:
  1431. params[new_name] = params.pop(old_name)
  1432. @_beartype.beartype
  1433. def _set_input_and_output_names(graph, input_names, output_names):
  1434. @_beartype.beartype
  1435. def set_names(node_list, name_list, descriptor):
  1436. if name_list is None:
  1437. return
  1438. if len(name_list) > len(node_list):
  1439. raise RuntimeError(
  1440. "number of %s names provided (%d) exceeded number of %ss (%d)"
  1441. % (descriptor, len(name_list), descriptor, len(node_list))
  1442. )
  1443. # Mark if the output node DebugName is set before.
  1444. output_node_set = set()
  1445. for i, (name, node) in enumerate(zip(name_list, node_list)):
  1446. # Duplicated output node, insert onnx::Identity to avoid setting the same DebugName after setDebugName().
  1447. if descriptor == "output":
  1448. if node in output_node_set:
  1449. identity_node = graph.create("onnx::Identity")
  1450. identity_node.insertAfter(node.node())
  1451. identity_node.addInput(node)
  1452. identity_node.output().setType(node.type())
  1453. graph.return_node().replaceInput(i, identity_node.output())
  1454. node = identity_node.output()
  1455. output_node_set.add(node)
  1456. if node.debugName() != name:
  1457. node.setDebugName(name)
  1458. set_names(list(graph.inputs()), input_names, "input")
  1459. set_names(list(graph.outputs()), output_names, "output")
  1460. @_beartype.beartype
  1461. def _run_symbolic_method(g, op_name, symbolic_fn, args):
  1462. r"""
  1463. This trampoline function gets invoked for every symbolic method
  1464. call from C++.
  1465. """
  1466. try:
  1467. graph_context = jit_utils.GraphContext(
  1468. graph=g,
  1469. block=g.block(),
  1470. opset=GLOBALS.export_onnx_opset_version,
  1471. original_node=None, # type: ignore[arg-type]
  1472. params_dict=_params_dict,
  1473. env={},
  1474. )
  1475. return symbolic_fn(graph_context, *args)
  1476. except TypeError as e:
  1477. # Handle the specific case where we didn't successfully dispatch
  1478. # to symbolic_fn. Otherwise, the backtrace will have the clues
  1479. # you need.
  1480. e.args = (f"{e.args[0]} (occurred when translating {op_name})",)
  1481. raise
  1482. @_beartype.beartype
  1483. def _add_block(node: _C.Node) -> _C.Block:
  1484. return node.addBlock()
  1485. @_beartype.beartype
  1486. def _add_input_to_block(block: _C.Block):
  1487. return block.addInputToBlock() # type: ignore[attr-defined]
  1488. @_beartype.beartype
  1489. def _add_output_to_block(block: _C.Block, value: _C.Value) -> int:
  1490. return block.registerOutput(value)
  1491. @_beartype.beartype
  1492. def _should_aten_fallback(
  1493. name: str, opset_version: int, operator_export_type: _C_onnx.OperatorExportTypes
  1494. ):
  1495. # For BUILD_CAFFE2=0 builds, if domain=="aten" and operator_export_type==ONNX_ATEN,
  1496. # an aten::ATen operator is created regardless of symbolics existence
  1497. # For BUILD_CAFFE2=1, the same applies only if there is no symbolic available
  1498. is_exportable_aten_op = registration.registry.is_registered_op(name, opset_version)
  1499. is_onnx_aten_export = operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN
  1500. is_aten_fallback_export = (
  1501. operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK
  1502. )
  1503. is_caffe2_build = _C_onnx._CAFFE2_ATEN_FALLBACK
  1504. if not name.startswith("aten::"):
  1505. return False
  1506. if is_caffe2_build:
  1507. if (
  1508. is_onnx_aten_export or is_aten_fallback_export
  1509. ) and not is_exportable_aten_op:
  1510. return True
  1511. else:
  1512. if is_onnx_aten_export or (
  1513. is_aten_fallback_export and not is_exportable_aten_op
  1514. ):
  1515. return True
  1516. return False
  1517. @_beartype.beartype
  1518. def _need_symbolic_context(symbolic_fn: Callable) -> bool:
  1519. """Checks if the first argument to symbolic_fn is annotated as type `torch.onnx.SymbolicContext`."""
  1520. params = tuple(inspect.signature(symbolic_fn).parameters.values())
  1521. # When the annotation is postpone-evaluated, the annotation is a string
  1522. # and not a type. We need to use get_type_hints to get the real type.
  1523. if not params:
  1524. return False
  1525. first_param_name = params[0].name
  1526. type_hints = typing.get_type_hints(symbolic_fn)
  1527. if first_param_name not in type_hints:
  1528. return False
  1529. param_type = type_hints[first_param_name]
  1530. return issubclass(param_type, _exporter_states.SymbolicContext)
  1531. @_beartype.beartype
  1532. def _symbolic_context_handler(symbolic_fn: Callable) -> Callable:
  1533. """Decorator that provides the symbolic context to the symbolic function if needed."""
  1534. if _need_symbolic_context(symbolic_fn):
  1535. # TODO(justinchuby): Update the module name of GraphContext when it is public
  1536. warnings.warn(
  1537. "The first argument to symbolic functions is deprecated in 1.13 and will be "
  1538. "removed in the future. Please annotate treat the first argument (g) as GraphContext "
  1539. "and use context information from the object instead.",
  1540. category=FutureWarning,
  1541. )
  1542. def wrapper(graph_context: jit_utils.GraphContext, *args, **kwargs):
  1543. symbolic_context = _exporter_states.SymbolicContext(
  1544. params_dict=graph_context.params_dict,
  1545. env=graph_context.env,
  1546. cur_node=graph_context.original_node,
  1547. onnx_block=graph_context.block,
  1548. )
  1549. return symbolic_fn(symbolic_context, graph_context, *args, **kwargs)
  1550. return wrapper
  1551. return symbolic_fn
  1552. @_beartype.beartype
  1553. def _get_aten_op_overload_name(n: _C.Node) -> str:
  1554. # Returns `overload_name` attribute to ATen ops on non-Caffe2 builds
  1555. schema = n.schema()
  1556. if not schema.startswith("aten::") or symbolic_helper.is_caffe2_aten_fallback():
  1557. return ""
  1558. return _C.parse_schema(schema).overload_name
  1559. @_beartype.beartype
  1560. def _run_symbolic_function(
  1561. graph: _C.Graph,
  1562. block: _C.Block,
  1563. node: _C.Node,
  1564. inputs: Any,
  1565. env: Dict[_C.Value, _C.Value],
  1566. operator_export_type=_C_onnx.OperatorExportTypes.ONNX,
  1567. ) -> Optional[Union[_C.Value, Sequence[Optional[_C.Value]]]]:
  1568. """Runs a symbolic function.
  1569. The function is used in C++ to export the node to ONNX.
  1570. Returns:
  1571. A single or a tuple of Values.
  1572. None when the node gets cloned as is into the new graph.
  1573. """
  1574. opset_version = GLOBALS.export_onnx_opset_version
  1575. # See Note [Export inplace]
  1576. node_kind = node.kind()
  1577. if node_kind.endswith("_"):
  1578. # Treat relu_ -> relu; add_ -> add etc.
  1579. ns_op_name = node_kind[:-1]
  1580. else:
  1581. ns_op_name = node_kind
  1582. namespace, op_name = jit_utils.parse_node_kind(ns_op_name)
  1583. graph_context = jit_utils.GraphContext(
  1584. graph=graph,
  1585. block=block,
  1586. opset=opset_version,
  1587. original_node=node,
  1588. params_dict=_params_dict,
  1589. env=env,
  1590. )
  1591. # Direct ATen export requested
  1592. if _should_aten_fallback(ns_op_name, opset_version, operator_export_type):
  1593. attrs = {
  1594. k + "_" + node.kindOf(k)[0]: symbolic_helper._node_get(node, k)
  1595. for k in node.attributeNames()
  1596. }
  1597. outputs = node.outputsSize()
  1598. attrs["outputs"] = outputs
  1599. return graph_context.aten_op(
  1600. op_name,
  1601. *inputs,
  1602. overload_name=_get_aten_op_overload_name(node),
  1603. **attrs,
  1604. )
  1605. try:
  1606. # Caffe2-specific: Quantized op symbolics are registered for opset 9 only.
  1607. if symbolic_helper.is_caffe2_aten_fallback() and opset_version == 9:
  1608. symbolic_caffe2.register_quantized_ops("caffe2", opset_version)
  1609. if namespace == "quantized" and symbolic_helper.is_caffe2_aten_fallback():
  1610. domain = "caffe2"
  1611. else:
  1612. domain = namespace
  1613. symbolic_function_name = f"{domain}::{op_name}"
  1614. symbolic_function_group = registration.registry.get_function_group(
  1615. symbolic_function_name
  1616. )
  1617. if symbolic_function_group is not None:
  1618. symbolic_fn = symbolic_function_group.get(opset_version)
  1619. if symbolic_fn is not None:
  1620. # TODO Wrap almost identical attrs assignment or comment the difference.
  1621. attrs = {
  1622. k: symbolic_helper._node_get(node, k) for k in node.attributeNames()
  1623. }
  1624. return symbolic_fn(graph_context, *inputs, **attrs)
  1625. attrs = {
  1626. k + "_" + node.kindOf(k)[0]: symbolic_helper._node_get(node, k)
  1627. for k in node.attributeNames()
  1628. }
  1629. if namespace == "onnx":
  1630. # Clone node to trigger ONNX shape inference
  1631. return graph_context.op(op_name, *inputs, **attrs, outputs=node.outputsSize()) # type: ignore[attr-defined]
  1632. raise errors.UnsupportedOperatorError(
  1633. symbolic_function_name,
  1634. opset_version,
  1635. symbolic_function_group.get_min_supported()
  1636. if symbolic_function_group
  1637. else None,
  1638. )
  1639. except RuntimeError:
  1640. if operator_export_type == _C_onnx.OperatorExportTypes.ONNX_FALLTHROUGH:
  1641. return None
  1642. elif (
  1643. operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK
  1644. and not symbolic_helper.is_caffe2_aten_fallback()
  1645. ):
  1646. # Emit ATen op for non-Caffe2 builds when `operator_export_type==ONNX_ATEN_FALLBACK`
  1647. attrs = {
  1648. k + "_" + node.kindOf(k)[0]: symbolic_helper._node_get(node, k)
  1649. for k in node.attributeNames()
  1650. }
  1651. return graph_context.aten_op(
  1652. op_name,
  1653. *inputs,
  1654. overload_name=_get_aten_op_overload_name(node),
  1655. **attrs,
  1656. )
  1657. raise
  1658. except TypeError as e:
  1659. # Handle the specific case where we didn't successfully dispatch.
  1660. # Otherwise, the backtrace will have the clues you need.
  1661. e.args = (f"{e.args[0]} \n(Occurred when translating {op_name}).",)
  1662. raise
  1663. @_beartype.beartype
  1664. def _verify_custom_op_name(symbolic_name: str):
  1665. if not re.match(r"^[a-zA-Z0-9-_]+::[a-zA-Z-_]+[a-zA-Z0-9-_]*$", symbolic_name):
  1666. raise errors.OnnxExporterError(
  1667. f"Failed to register operator {symbolic_name}. "
  1668. "The symbolic name must match the format domain::name, "
  1669. "and should start with a letter and contain only "
  1670. "alphanumerical characters"
  1671. )
  1672. ns, _ = jit_utils.parse_node_kind(symbolic_name)
  1673. if ns == "onnx":
  1674. raise ValueError(
  1675. f"Failed to register operator {symbolic_name}. {ns} domain cannot be modified."
  1676. )
  1677. @_beartype.beartype
  1678. def register_custom_op_symbolic(
  1679. symbolic_name: str,
  1680. symbolic_fn: Callable,
  1681. opset_version: int,
  1682. ):
  1683. """Registers a symbolic function for a custom operator.
  1684. When the user registers symbolic for custom/contrib ops,
  1685. it is highly recommended to add shape inference for that operator via setType API,
  1686. otherwise the exported graph may have incorrect shape inference in some extreme cases.
  1687. An example of setType is `test_aten_embedding_2` in `test_operators.py`.
  1688. See "Custom Operators" in the module documentation for an example usage.
  1689. Args:
  1690. symbolic_name (str): The name of the custom operator in "<domain>::<op>"
  1691. format.
  1692. symbolic_fn (Callable): A function that takes in the ONNX graph and
  1693. the input arguments to the current operator, and returns new
  1694. operator nodes to add to the graph.
  1695. opset_version (int): The ONNX opset version in which to register.
  1696. """
  1697. if symbolic_name.startswith("::"):
  1698. symbolic_name = f"aten{symbolic_name}"
  1699. _verify_custom_op_name(symbolic_name)
  1700. registration.custom_onnx_symbolic(
  1701. symbolic_name,
  1702. opset_version,
  1703. decorate=[
  1704. _symbolic_context_handler,
  1705. ],
  1706. )(symbolic_fn)
  1707. @_beartype.beartype
  1708. def unregister_custom_op_symbolic(symbolic_name: str, opset_version: int):
  1709. """Unregisters ``symbolic_name``.
  1710. See "Custom Operators" in the module documentation for an example usage.
  1711. Args:
  1712. symbolic_name (str): The name of the custom operator in "<domain>::<op>"
  1713. format.
  1714. opset_version (int): The ONNX opset version in which to unregister.
  1715. """
  1716. if symbolic_name.startswith("::"):
  1717. symbolic_name = f"aten{symbolic_name}"
  1718. _verify_custom_op_name(symbolic_name)
  1719. registration.registry.unregister(symbolic_name, opset_version)
  1720. @_beartype.beartype
  1721. def _validate_dynamic_axes(dynamic_axes, model, input_names, output_names):
  1722. """Ensures dynamic axes argument is follows the expected format."""
  1723. if len(dynamic_axes) == 0:
  1724. return
  1725. if hasattr(model, "graph"):
  1726. # Extracting set of valid input/output names that shall be used for dynamic_axes
  1727. if (input_names is None) or len(input_names) == 0:
  1728. input_names = [x.debugName() for x in model.graph.inputs()]
  1729. if (output_names is None) or len(output_names) == 0:
  1730. output_names = [y.debugName() for y in model.graph.outputs()]
  1731. valid_names = set((input_names or []) + (output_names or []))
  1732. # If dynamic axes are provided as a list rather than dictionary, they should
  1733. # first get converted to a dictionary in expected format. If desired axes names
  1734. # are not provided for dynamic axes, automatic names shall be generated for
  1735. # provided dynamic axes of specified input/output
  1736. for key, value in dynamic_axes.items():
  1737. if key not in valid_names:
  1738. warnings.warn(
  1739. f"Provided key {key} for dynamic axes is not a valid input/output name"
  1740. )
  1741. if isinstance(value, list):
  1742. warnings.warn(
  1743. "No names were found for specified dynamic axes of provided input."
  1744. f"Automatically generated names will be applied to each dynamic axes of input {key}"
  1745. )
  1746. value_dict = {}
  1747. for i, x in enumerate(value):
  1748. if not isinstance(x, int):
  1749. raise ValueError(
  1750. "The type of axis index is expected to be an integer"
  1751. )
  1752. if x in value_dict:
  1753. warnings.warn(
  1754. f"Duplicate dynamic axis index {x} was provided for input {key}."
  1755. )
  1756. else:
  1757. value_dict[x] = str(key) + "_dynamic_axes_" + str(i + 1)
  1758. dynamic_axes[key] = value_dict