symbolic_helper.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. from __future__ import annotations
  2. import enum
  3. import functools
  4. import inspect
  5. import sys
  6. import warnings
  7. from typing import Any, Callable, List, Optional, Sequence, Set, Tuple, Union
  8. import torch
  9. import torch._C._onnx as _C_onnx
  10. import torch.onnx
  11. from torch import _C
  12. # This import monkey-patches graph manipulation methods on Graph, used for the
  13. # ONNX symbolics
  14. from torch.onnx import _patch_torch # noqa: F401
  15. from torch.onnx._globals import GLOBALS
  16. # Note [Edit Symbolic Files]
  17. # EDITING THIS FILE AND SYMBOLIC_OPSET<VERSION> FILES? READ THIS FIRST!
  18. #
  19. # - Module-level functions are called to convert the corresponding op in the `aten` domain.
  20. # E.g. symbolic_opset9.foo is called to convert aten::foo.
  21. # Symbolic functions for other domains are staticmethods in classes named after the domain.
  22. # E.g. symbolic_opset9.Prim.ConstantChunk is called to convert prim::ConstantChunk.
  23. # - Parameter names must *exactly* match the names in
  24. # aten/src/ATen/native/native_functions.yaml, because
  25. # dispatch is done with keyword arguments.
  26. # - Looking for inplace ops? They're detected by
  27. # `_jit_pass_onnx_remove_inplace_ops_for_onnx`, and
  28. # transparently dispatched to their non inplace versions in
  29. # "run_symbolic_function". See Note [Export inplace]
  30. #
  31. # ----------------------------------------------------------------------------------
  32. # A note on Tensor types
  33. # ----------------------------------------------------------------------------------
  34. #
  35. # In general, we should avoid depending on the type of Tensor Values contained
  36. # within the trace graph. However, this is sometimes unavoidable (due to ONNX
  37. # spec requirements, etc). The TensorType object has accessors for these properties
  38. # that return the property if it is statically known and return nullopt otherwise.
  39. #
  40. # In general, we should prefer to rely on the least specific information possible.
  41. # For example, not relying on tensor properties at all is better than relying
  42. # on the number of dimensions which is better than relying on
  43. # concrete shapes. Doing so will make the export symbolics
  44. # more robust to different graphs.
  45. #
  46. # ----------------------------------------------------------------------------------
  47. # Extra context for symbolic functions
  48. # ----------------------------------------------------------------------------------
  49. #
  50. # In general, symbolic functions only require inputs and attributes to
  51. # the original node. In rare circumstances, extra context may be required.
  52. # For example, symbolic function for `prim::Loop` needs access to the subblock of
  53. # the original node.
  54. # A symbolic function that has a first arg (before the Graph object) with the
  55. # type annotation of torch.onnx.SymbolicContext will be called with that additional context.
  56. # During export, it is populated from `utils._run_symbolic_function`
  57. # to contain the context for each node being converted.
  58. # ---------------------------------------------------------------------------------
  59. # Helper functions
  60. # ---------------------------------------------------------------------------------
  61. def _parse_arg(value, desc, arg_name=None, node_name=None):
  62. if desc == "none":
  63. return value
  64. if desc == "v" or not _is_value(value):
  65. return value
  66. if value.node().mustBeNone():
  67. return None
  68. if value.node().kind() == "onnx::Constant":
  69. tval = value.node()["value"]
  70. if desc == "i":
  71. return int(tval)
  72. elif desc == "f":
  73. return float(tval)
  74. elif desc == "b":
  75. return bool(tval)
  76. elif desc == "s":
  77. return str(tval)
  78. elif desc == "t":
  79. return tval
  80. elif desc == "is":
  81. return [int(v) for v in tval]
  82. elif desc == "fs":
  83. return [float(v) for v in tval]
  84. else:
  85. raise RuntimeError("ONNX symbolic doesn't know to interpret Constant node")
  86. elif value.node().kind() == "prim::ListConstruct":
  87. if desc == "is":
  88. for v in value.node().inputs():
  89. if v.node().kind() != "onnx::Constant":
  90. raise RuntimeError(
  91. "Failed to export an ONNX attribute '"
  92. + v.node().kind()
  93. + "', since it's not constant, please try to make "
  94. "things (e.g., kernel size) static if possible"
  95. )
  96. return [int(v.node()["value"]) for v in value.node().inputs()]
  97. else:
  98. raise RuntimeError(
  99. "ONNX symbolic doesn't know to interpret ListConstruct node"
  100. )
  101. if arg_name is None or node_name is None:
  102. raise RuntimeError(
  103. "Expected node type 'onnx::Constant', got '{}'.".format(value.node().kind())
  104. )
  105. else:
  106. raise RuntimeError(
  107. "Expected node type 'onnx::Constant' "
  108. "for argument '{}' of node '{}', got '{}'.".format(
  109. arg_name, node_name, value.node().kind()
  110. )
  111. )
  112. def _maybe_get_const(value, desc):
  113. if _is_value(value) and value.node().kind() == "onnx::Constant":
  114. return _parse_arg(value, desc)
  115. return value
  116. def _maybe_get_scalar(value):
  117. value_t = _maybe_get_const(value, "t")
  118. if isinstance(value_t, torch.Tensor) and value_t.shape == ():
  119. return value_t
  120. return value
  121. def _get_const(value, desc, arg_name):
  122. if not _is_constant(value):
  123. raise RuntimeError(
  124. "ONNX symbolic expected a constant value of the {} argument, got `{}`".format(
  125. arg_name, value
  126. )
  127. )
  128. return _parse_arg(value, desc)
  129. def _unpack_list(list_value: _C.Value) -> List[_C.Value]:
  130. list_node = list_value.node()
  131. assert list_node.kind() == "prim::ListConstruct"
  132. return list(list_node.inputs())
  133. def _unpack_tuple(tuple_value):
  134. tuple_node = tuple_value.node()
  135. if tuple_node.kind() != "prim::TupleConstruct":
  136. raise RuntimeError(
  137. "ONNX symbolic expected node type `prim::TupleConstruct`, got `{}`".format(
  138. tuple_node
  139. )
  140. )
  141. return list(tuple_node.inputs())
  142. # Check if list_value is output from prim::ListConstruct
  143. # This is usually called before _unpack_list to ensure the list can be unpacked.
  144. def _is_packed_list(list_value):
  145. return _is_value(list_value) and list_value.node().kind() == "prim::ListConstruct"
  146. def parse_args(*arg_descriptors):
  147. """A decorator which converts args from torch._C.Value to built-in types.
  148. For example:
  149. ```
  150. @parse_args('v', 'i', 'fs')
  151. foo(g, a, b, c):
  152. assert isinstance(a, torch._C.Value)
  153. assert isinstance(b, int)
  154. assert isinstance(c, list)
  155. assert isinstance(c[0], float)
  156. ```
  157. Args:
  158. arg_descriptors: list of str, where each element is
  159. a string that specifies the type to convert to. Valid descriptors:
  160. "v": no conversion, keep torch._C.Value.
  161. "i": int
  162. "is": list of int
  163. "f": float
  164. "fs": list of float
  165. "b": bool
  166. "s": str
  167. "t": torch.Tensor
  168. """
  169. def decorator(fn):
  170. fn._arg_descriptors = arg_descriptors
  171. @functools.wraps(fn)
  172. def wrapper(g, *args, **kwargs):
  173. # some args may be optional, so the length may be smaller
  174. FILE_BUG_MSG = (
  175. "If you believe this is not due to custom symbolic implementation within your code or "
  176. "an external library, please file an issue at "
  177. "https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to report this bug."
  178. )
  179. assert len(arg_descriptors) >= len(args), (
  180. f"A mismatch between the number of arguments ({len(args)}) and "
  181. f"their descriptors ({len(arg_descriptors)}) was found at symbolic function '{fn.__name__}'. "
  182. f"{FILE_BUG_MSG}"
  183. )
  184. try:
  185. sig = inspect.signature(fn)
  186. arg_names = list(sig.parameters.keys())[1:]
  187. fn_name = fn.__name__
  188. except Exception:
  189. arg_names = [None] * len(args) # type: ignore[list-item]
  190. fn_name = None
  191. args = [
  192. _parse_arg(arg, arg_desc, arg_name, fn_name) # type: ignore[assignment]
  193. for arg, arg_desc, arg_name in zip(args, arg_descriptors, arg_names)
  194. ]
  195. # only support _outputs in kwargs
  196. assert len(kwargs) <= 1, (
  197. f"Symbolic function {fn.__name__}'s '**kwargs' can contain a single key/value entry. "
  198. f"{FILE_BUG_MSG}"
  199. )
  200. if len(kwargs) == 1:
  201. assert "_outputs" in kwargs, (
  202. f"Symbolic function {fn.__name__}'s '**kwargs' can only contain '_outputs' key at '**kwargs'. "
  203. f"{FILE_BUG_MSG}"
  204. )
  205. return fn(g, *args, **kwargs)
  206. return wrapper
  207. return decorator
  208. def quantized_args(
  209. *arg_q_descriptors: bool,
  210. scale: Optional[float] = None,
  211. zero_point: Optional[int] = None,
  212. ):
  213. """A decorator which extends support for quantized version of the base operator.
  214. Quantization is detected by examining the arguments that are annotated by
  215. `arg_q_descriptors`.
  216. If quantization is detected, the base operator symbolic function will be wrapped with
  217. argument de-quantization and output quantization.
  218. Otherwise, only the base symbolic function will be invoked.
  219. For example:
  220. ```
  221. @quantized_args(True, False)
  222. def foo(g, x, y):
  223. return x + y
  224. ```
  225. is equivalent to
  226. ```
  227. def q_foo(g, x, y):
  228. if is_quantized_tensor(x):
  229. x = dequantize(x)
  230. out = foo(g, x, y)
  231. return quantize(out)
  232. else:
  233. return foo(g, x, y)
  234. ```
  235. Args:
  236. arg_q_descriptors: A sequence of bool, where each element represents if the
  237. argument is QTensor for quantized version of this operator. It defaults
  238. to False for unspecified (variable length) arguments.
  239. scale: Quantized output scale. If None, derive from
  240. the first quantized input scale.
  241. zero_point: Quantized output zero point. If None,
  242. derive from the first quantized input zero point.
  243. """
  244. def decorator(fn):
  245. fn._scale = scale
  246. fn._zero_point = zero_point
  247. @functools.wraps(fn)
  248. def wrapper(g, *args, **kwargs):
  249. _scale = fn._scale
  250. if _scale is not None:
  251. _scale = g.op("Constant", value_t=torch.tensor(_scale))
  252. _zero_point = fn._zero_point
  253. if _zero_point is not None:
  254. _zero_point = g.op("Constant", value_t=torch.tensor(_zero_point))
  255. # Support variable length arguments by marking unspecified ones as non-quantized
  256. arg_q_descriptors_extended = arg_q_descriptors + (False,) * (
  257. len(args) - len(arg_q_descriptors)
  258. )
  259. descriptor_args = tuple(zip(arg_q_descriptors_extended, args))
  260. # Run regular symbolic function if none of the argument is QTensor.
  261. if not any(
  262. (descriptor and arg.node().kind() == "prim::TupleConstruct")
  263. for descriptor, arg in descriptor_args
  264. ):
  265. return fn(g, *args, **kwargs)
  266. dequantized_args = []
  267. for descriptor, arg in descriptor_args:
  268. if descriptor:
  269. dequantized_arg, scale, zero_point, _ = dequantize_helper(g, arg)
  270. dequantized_args.append(dequantized_arg)
  271. if _scale is None:
  272. _scale = scale
  273. if _zero_point is None:
  274. _zero_point = zero_point
  275. else:
  276. dequantized_args.append(arg)
  277. # TODO(justinchuby): Only single output is supported for now. We may want to
  278. # support multiple outputs in the future.
  279. output = fn(g, *dequantized_args, **kwargs)
  280. return quantize_helper(g, output, _scale, _zero_point)
  281. return wrapper
  282. return decorator
  283. def _scalar(x):
  284. """Convert a scalar tensor into a Python value."""
  285. assert x.numel() == 1
  286. return x.item()
  287. def _if_scalar_type_as(g: _C.Graph, self, tensor):
  288. """
  289. Convert self into the same type of tensor, as necessary.
  290. We only support implicit casting for scalars, so we never
  291. actually need to insert an ONNX cast operator here; just
  292. fix up the scalar.
  293. """
  294. if isinstance(self, _C.Value):
  295. return self
  296. scalar_type = tensor.type().scalarType()
  297. if scalar_type:
  298. ty = scalar_type.lower()
  299. return getattr(self, ty)()
  300. return self
  301. def _is_none(x):
  302. return x.node().mustBeNone()
  303. def _is_value(x):
  304. return isinstance(x, _C.Value)
  305. def _is_constant(value):
  306. return not _is_value(value) or value.node().kind() in (
  307. "onnx::Constant",
  308. "prim::Constant",
  309. )
  310. def _is_tensor(x):
  311. return x.type().isSubtypeOf(_C.TensorType.get())
  312. def _is_list(x):
  313. return isinstance(x.type(), _C.ListType)
  314. def _is_tensor_list(x):
  315. return _is_list(x) and isinstance(x.type().getElementType(), _C.TensorType)
  316. def _is_scalar_list(x):
  317. """Checks if x is a scalar list, for example: List[float], List[int].
  318. Besides checking the type is ListType, we also check if the data type is
  319. a valid ONNX data type.
  320. """
  321. element_type = str(x.type().getElementType())
  322. return (
  323. _is_list(x)
  324. and element_type in scalar_name_to_pytorch.keys()
  325. and (scalar_name_to_pytorch[element_type] in cast_pytorch_to_onnx.keys())
  326. )
  327. def is_caffe2_aten_fallback():
  328. return (
  329. GLOBALS.operator_export_type == _C_onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK
  330. and _C_onnx._CAFFE2_ATEN_FALLBACK
  331. )
  332. def _get_tensor_rank(x):
  333. if not _is_tensor(x) or x.type() is None:
  334. return None
  335. return x.type().dim()
  336. def _get_tensor_sizes(x, allow_nonstatic=True):
  337. if not _is_tensor(x) or x.type() is None:
  338. return None
  339. if allow_nonstatic:
  340. # Each individual symbol is returned as None.
  341. # e.g. [1, "a", "b"] -> [1, None, None]
  342. return x.type().varyingSizes()
  343. # returns None, if exists any symbol in sizes.
  344. # e.g. [1, "a", "b"] -> None
  345. return x.type().sizes()
  346. def _get_tensor_dim_size(x, dim):
  347. try:
  348. sizes = _get_tensor_sizes(x)
  349. return sizes[dim]
  350. except Exception:
  351. pass
  352. return None
  353. def _get_dim_for_cross(input, dim):
  354. if dim == -1:
  355. return dim + _get_tensor_rank(input)
  356. # If dim is not given, it defaults to the first dimension found with the size 3
  357. if dim is None:
  358. sizes = _get_tensor_sizes(input)
  359. for index, size in enumerate(sizes):
  360. if size is not None and size == 3:
  361. return index
  362. return dim
  363. def _unimplemented(op, msg):
  364. # For BC reasons, the behavior for Caffe2 does not raise exception for unimplemented operators
  365. if _C_onnx._CAFFE2_ATEN_FALLBACK:
  366. warnings.warn(
  367. "ONNX export failed on " + op + " because " + msg + " not supported"
  368. )
  369. elif GLOBALS.operator_export_type == _C_onnx.OperatorExportTypes.ONNX:
  370. _onnx_unsupported(f"{op}, {msg}")
  371. def _onnx_unsupported(op_name):
  372. raise RuntimeError(
  373. "Unsupported: ONNX export of operator {}. "
  374. "Please feel free to request support or submit a pull request on PyTorch GitHub.".format(
  375. op_name
  376. )
  377. )
  378. def _onnx_opset_unsupported(op_name, current_opset, supported_opset):
  379. raise RuntimeError(
  380. "Unsupported: ONNX export of {} in "
  381. "opset {}. Please try opset version {}.".format(
  382. op_name, current_opset, supported_opset
  383. )
  384. )
  385. def _onnx_opset_unsupported_detailed(op_name, current_opset, supported_opset, reason):
  386. raise RuntimeError(
  387. "Unsupported: ONNX export of {} in "
  388. "opset {}. {}. Please try opset version {}.".format(
  389. op_name, current_opset, reason, supported_opset
  390. )
  391. )
  392. def _block_list_in_opset(name):
  393. def symbolic_fn(*args, **kwargs):
  394. raise RuntimeError(
  395. "ONNX export failed on {}, which is not implemented for opset {}. "
  396. "Try exporting with other opset versions.".format(
  397. name, GLOBALS.export_onnx_opset_version
  398. )
  399. )
  400. return symbolic_fn
  401. def _try_get_scalar_type(*args):
  402. for arg in args:
  403. try:
  404. return arg.type().scalarType()
  405. except RuntimeError:
  406. pass
  407. return None
  408. def _select_helper(g, self, dim, index, apply_reshape=True):
  409. index_const = _maybe_get_scalar(index)
  410. index_dim = _get_tensor_rank(index)
  411. if not _is_value(index_const):
  412. # Index is a constant scalar. Make it a size 1 constant tensor.
  413. index = g.op("Constant", value_t=torch.LongTensor([index_const]))
  414. elif index_dim is not None and apply_reshape:
  415. if index_dim == 0:
  416. # Index is a scalar. Reshape it to a size 1 tensor.
  417. index = _reshape_helper(
  418. g, index, g.op("Constant", value_t=torch.LongTensor([1]))
  419. )
  420. index_scalar_type = index.type().scalarType()
  421. if index_scalar_type is None or index_scalar_type not in ["Long", "Int"]:
  422. index = g.op("Cast", index, to_i=cast_pytorch_to_onnx["Long"])
  423. return g.op("Gather", self, index, axis_i=dim)
  424. def _slice_helper(g, input, axes, starts, ends, steps=None, dynamic_slice=False):
  425. if GLOBALS.export_onnx_opset_version <= 9:
  426. from torch.onnx.symbolic_opset9 import _slice as _slice9
  427. return _slice9(g, input, axes, starts, ends)
  428. else:
  429. from torch.onnx.symbolic_opset10 import _slice as _slice10
  430. return _slice10(g, input, axes, starts, ends, steps, dynamic_slice)
  431. def _is_fp(value):
  432. if value:
  433. if isinstance(value, torch.Tensor):
  434. return value.dtype in (
  435. torch.float16,
  436. torch.float32,
  437. torch.float64,
  438. torch.bfloat16,
  439. )
  440. else:
  441. type = value.type().scalarType()
  442. if type is None:
  443. warnings.warn(
  444. "Type cannot be inferred, which might cause exported graph to produce incorrect results."
  445. )
  446. return type in ("Float", "Double", "Half", "BFloat16")
  447. return False
  448. def _generate_wrapped_number(g, scalar):
  449. """Creates a wrapped number based on https://github.com/pytorch/pytorch/issues/9515.
  450. A Tensor is a considered a "wrapped number" if it is
  451. auto-wrapped from a C++ or Python number type. Integer types are
  452. wrapped as 0-dim int64 tensors and floating-point types are
  453. wrapped as 0-dim double tensors.
  454. The input to this function is constant value. If the data type
  455. is a floating point type, it is converted to a 0-dim double
  456. tensor, else it is converted to a 0-dim tensor of its original type
  457. """
  458. assert not isinstance(scalar, torch.Tensor)
  459. if isinstance(scalar, float):
  460. return g.op("Constant", value_t=torch.tensor(scalar, dtype=torch.double))
  461. return g.op("Constant", value_t=torch.tensor(scalar))
  462. def _sort_helper(g, input, dim, decending=True, out=None):
  463. if out is not None:
  464. _unimplemented("Sort", "Out parameter is not supported")
  465. shape_ = g.op("Shape", input)
  466. dim_size_ = g.op(
  467. "Gather",
  468. shape_,
  469. g.op("Constant", value_t=torch.tensor([dim], dtype=torch.int64)),
  470. )
  471. if GLOBALS.export_onnx_opset_version <= 10:
  472. if not decending:
  473. _unimplemented("Sort", "Ascending is not supported")
  474. return g.op("TopK", input, dim_size_, axis_i=dim, outputs=2)
  475. else:
  476. return g.op(
  477. "TopK", input, dim_size_, axis_i=dim, largest_i=decending, outputs=2
  478. )
  479. def _topk_helper(g, input, k, dim, largest=True, sorted=False, out=None):
  480. if out is not None:
  481. _unimplemented("TopK", "Out parameter is not supported")
  482. if not _is_value(k):
  483. k = g.op("Constant", value_t=torch.tensor([k], dtype=torch.int64))
  484. else:
  485. k = _reshape_helper(g, k, g.op("Constant", value_t=torch.tensor([1])))
  486. if _try_get_scalar_type(k) != "Long":
  487. k = g.op("Cast", k, to_i=_C_onnx.TensorProtoDataType.INT64)
  488. if GLOBALS.export_onnx_opset_version <= 10:
  489. if not largest:
  490. _unimplemented("TopK", "Ascending is not supported")
  491. return g.op("TopK", input, k, axis_i=dim, outputs=2)
  492. else:
  493. return g.op(
  494. "TopK", input, k, axis_i=dim, largest_i=largest, sorted_i=sorted, outputs=2
  495. )
  496. def _lt_helper(g, input, other):
  497. if GLOBALS.export_onnx_opset_version <= 8:
  498. from torch.onnx.symbolic_opset8 import lt as _lt8
  499. return _lt8(g, input, other)
  500. else:
  501. from torch.onnx.symbolic_opset9 import lt as _lt9
  502. return _lt9(g, input, other)
  503. def _interpolate_warning(interpolate_mode):
  504. onnx_op = (
  505. "onnx:Resize" if GLOBALS.export_onnx_opset_version >= 10 else "onnx:Upsample"
  506. )
  507. warnings.warn(
  508. "You are trying to export the model with "
  509. + onnx_op
  510. + " for ONNX opset version "
  511. "" + str(GLOBALS.export_onnx_opset_version) + ". "
  512. "This operator might cause results to not match the expected results by PyTorch.\n"
  513. "ONNX's Upsample/Resize operator did not match Pytorch's Interpolation until opset 11. "
  514. "Attributes to determine how to transform the input were added in onnx:Resize in opset 11 "
  515. "to support Pytorch's behavior (like coordinate_transformation_mode and nearest_mode).\n"
  516. "We recommend using opset 11 and above for models using this operator."
  517. )
  518. def _unsqueeze_helper(g, input, axes_i):
  519. if _is_constant(axes_i[0]):
  520. if GLOBALS.export_onnx_opset_version >= 13:
  521. axes = g.op("Constant", value_t=torch.tensor(axes_i, dtype=torch.long))
  522. return g.op("Unsqueeze", input, axes)
  523. return g.op("Unsqueeze", input, axes_i=axes_i)
  524. # Tensor type
  525. if GLOBALS.export_onnx_opset_version < 13:
  526. raise ValueError(
  527. f"Opset version must be >= 13 for Unsqueeze with dynamic axes. {input.node().sourceRange()}"
  528. )
  529. return g.op("Unsqueeze", input, axes_i[0])
  530. def _squeeze_helper(g, input, axes_i):
  531. if _is_constant(axes_i[0]):
  532. if GLOBALS.export_onnx_opset_version >= 13:
  533. axes = g.op("Constant", value_t=torch.tensor(axes_i, dtype=torch.long))
  534. return g.op("Squeeze", input, axes)
  535. return g.op("Squeeze", input, axes_i=axes_i)
  536. # Tensor type
  537. if GLOBALS.export_onnx_opset_version < 13:
  538. raise ValueError(
  539. f"Opset version must be >= 13 for Squeeze with dynamic axes. {input.node().sourceRange()}"
  540. )
  541. axes_t = axes_i[0]
  542. axes_rank = _get_tensor_rank(axes_t)
  543. if axes_rank > 1:
  544. raise ValueError(
  545. "For Squeeze axses as input, the axes rank must be one in ONNX spec."
  546. )
  547. elif axes_rank == 0:
  548. # The axes is a scalar. Unsqueeze it to a rank 1 tensor.
  549. axes_t = _unsqueeze_helper(g, axes_t, [0])
  550. return g.op("Squeeze", input, axes_t)
  551. return g.op("Squeeze", input, axes_t)
  552. def _reducesum_helper(g, input, axes_i=None, keepdims_i=1, noop_with_empty_axes_i=0):
  553. keepdims_i = _maybe_get_const(keepdims_i, "i")
  554. if GLOBALS.export_onnx_opset_version >= 13:
  555. if axes_i:
  556. if not _is_value(axes_i):
  557. axes_i = g.op(
  558. "Constant", value_t=torch.tensor(axes_i, dtype=torch.long)
  559. )
  560. return g.op(
  561. "ReduceSum",
  562. input,
  563. axes_i,
  564. keepdims_i=keepdims_i,
  565. noop_with_empty_axes_i=noop_with_empty_axes_i,
  566. )
  567. return g.op(
  568. "ReduceSum",
  569. input,
  570. keepdims_i=keepdims_i,
  571. noop_with_empty_axes_i=noop_with_empty_axes_i,
  572. )
  573. else:
  574. return g.op("ReduceSum", input, axes_i=axes_i, keepdims_i=keepdims_i)
  575. def _interpolate_size_to_scales(g, input, output_size, dim):
  576. output_size = _maybe_get_const(output_size, "is")
  577. if _is_value(output_size):
  578. offset = 2
  579. offsets = g.op("Constant", value_t=torch.ones(offset, dtype=torch.float32))
  580. dividend = g.op("Cast", output_size, to_i=cast_pytorch_to_onnx["Float"])
  581. divisor = _slice_helper(
  582. g, g.op("Shape", input), axes=[0], ends=[sys.maxsize], starts=[offset]
  583. )
  584. divisor = g.op("Cast", divisor, to_i=cast_pytorch_to_onnx["Float"])
  585. scale_dims = g.op("Div", dividend, divisor)
  586. scales = g.op("Concat", offsets, scale_dims, axis_i=0)
  587. else:
  588. scales_constant = [
  589. 1.0
  590. if i < 2
  591. else float(output_size[-(dim - i)])
  592. / float(input.type().sizes()[-(dim - i)])
  593. for i in range(0, dim)
  594. ]
  595. scales = g.op(
  596. "Constant", value_t=torch.tensor(scales_constant, dtype=torch.float32)
  597. )
  598. return scales
  599. def _interpolate_get_scales_if_available(g, scales):
  600. available_scales = _maybe_get_const(scales[0], "fs") != -1 and not _is_none(
  601. scales[0]
  602. )
  603. if not available_scales:
  604. return None
  605. offsets = g.op("Constant", value_t=torch.ones(2, dtype=torch.float32))
  606. scales_list = g.op(
  607. "Constant", value_t=torch.tensor(_maybe_get_const(scales[0], "fs"))
  608. )
  609. scales = g.op("Concat", offsets, scales_list, axis_i=0)
  610. return scales
  611. def _get_interpolate_attributes(g, mode, args):
  612. if mode == "nearest":
  613. align_corners = None
  614. scales = args[0:]
  615. else:
  616. align_corners = args[0]
  617. scales = args[1:]
  618. scales = _interpolate_get_scales_if_available(g, scales)
  619. return scales, align_corners
  620. def _interpolate_get_scales(g, scale_factor, dim):
  621. offsets = g.op("Constant", value_t=torch.ones(2, dtype=torch.float32))
  622. scale_factor_rank = _get_tensor_rank(scale_factor)
  623. if isinstance(scale_factor.type(), _C.ListType) or (
  624. scale_factor_rank is not None and scale_factor_rank > 0
  625. ):
  626. return g.op("Concat", offsets, scale_factor, axis_i=0)
  627. else:
  628. scale_factor = _unsqueeze_helper(g, scale_factor, [0])
  629. scale_factor = g.op("Cast", scale_factor, to_i=cast_pytorch_to_onnx["Float"])
  630. scales = [scale_factor for i in range(dim - 2)]
  631. scale_factor = g.op("Concat", offsets, *scales, axis_i=0)
  632. return scale_factor
  633. def _interpolate_get_scales_and_mode(g, input, size, scale_factor, mode, align_corners):
  634. mode = _maybe_get_const(mode, "s")
  635. if "linear" in mode:
  636. mode = "linear"
  637. if "cubic" in mode:
  638. mode = "cubic"
  639. _interpolate_warning(mode)
  640. align_corners = _maybe_get_const(align_corners, "b")
  641. if isinstance(align_corners, bool) and align_corners:
  642. return _unimplemented("interpolate", "align_corners == True")
  643. if not input.type().dim():
  644. return _unimplemented("interpolate", "missing input shape")
  645. dim = input.type().dim()
  646. if not _is_none(scale_factor):
  647. scale_factor = _interpolate_get_scales(g, scale_factor, dim)
  648. elif not _is_none(size):
  649. if not _is_packed_list(size):
  650. is_scalar = _maybe_get_const(size, "t").dim() == 0
  651. if is_scalar:
  652. size = _unsqueeze_helper(g, size, [0])
  653. size = [size for i in range(dim - 2)]
  654. size = g.op("Concat", *size, axis_i=0)
  655. scale_factor = _interpolate_size_to_scales(g, input, size, dim)
  656. else:
  657. return _unimplemented(
  658. "interpolate", "Both size and scales are None in __interpolate"
  659. )
  660. return scale_factor, mode
  661. def _interpolate_helper(name, dim, interpolate_mode):
  662. @quantized_args(True, False, False)
  663. def symbolic_fn(g, input, output_size, *args):
  664. scales, align_corners = _get_interpolate_attributes(g, interpolate_mode, args)
  665. align_corners = _maybe_get_scalar(align_corners)
  666. coordinate_transformation_mode = (
  667. "asymmetric"
  668. if interpolate_mode == "nearest"
  669. else "align_corners"
  670. if align_corners
  671. else "pytorch_half_pixel"
  672. )
  673. if scales is None:
  674. input_size = g.op("Shape", input)
  675. input_size_beg = _slice_helper(
  676. g, input_size, axes=[0], ends=[2], starts=[0]
  677. )
  678. output_size = g.op("Cast", output_size, to_i=cast_pytorch_to_onnx["Long"])
  679. output_size = g.op("Concat", input_size_beg, output_size, axis_i=0)
  680. if GLOBALS.export_onnx_opset_version >= 13:
  681. empty_roi = _optional_input_placeholder_tensor(g)
  682. empty_scales = _optional_input_placeholder_tensor(g)
  683. else:
  684. empty_roi = g.op(
  685. "Constant", value_t=torch.tensor([], dtype=torch.float32)
  686. )
  687. empty_scales = g.op(
  688. "Constant", value_t=torch.tensor([], dtype=torch.float32)
  689. )
  690. return g.op(
  691. "Resize",
  692. input,
  693. empty_roi,
  694. empty_scales,
  695. output_size,
  696. coordinate_transformation_mode_s=coordinate_transformation_mode,
  697. cubic_coeff_a_f=-0.75, # only valid when mode="cubic"
  698. mode_s=interpolate_mode, # nearest, linear, or cubic
  699. nearest_mode_s="floor",
  700. ) # only valid when mode="nearest"
  701. else:
  702. if GLOBALS.export_onnx_opset_version >= 13:
  703. empty_roi = _optional_input_placeholder_tensor(g)
  704. else:
  705. empty_roi = g.op(
  706. "Constant", value_t=torch.tensor([], dtype=torch.float32)
  707. )
  708. return g.op(
  709. "Resize",
  710. input,
  711. empty_roi,
  712. scales,
  713. coordinate_transformation_mode_s=coordinate_transformation_mode,
  714. cubic_coeff_a_f=-0.75, # only valid when mode="cubic"
  715. mode_s=interpolate_mode, # nearest, linear, or cubic
  716. nearest_mode_s="floor",
  717. ) # only valid when mode="nearest"
  718. return symbolic_fn
  719. def __interpolate_helper(
  720. g, input, size, scale_factor, mode, align_corners, recompute_scale_factor
  721. ):
  722. mode = _maybe_get_const(mode, "s")
  723. if "linear" in mode:
  724. mode = "linear"
  725. if "cubic" in mode:
  726. mode = "cubic"
  727. align_corners = _maybe_get_const(align_corners, "b")
  728. align_corners = False if not isinstance(align_corners, bool) else align_corners
  729. coordinate_transformation_mode = (
  730. "asymmetric"
  731. if mode == "nearest"
  732. else "align_corners"
  733. if align_corners
  734. else "pytorch_half_pixel"
  735. )
  736. if not _is_none(size):
  737. input_size = g.op("Shape", input)
  738. input_size = _slice_helper(g, input_size, axes=[0], ends=[2], starts=[0])
  739. # in some cases size is not a packed list but size is a scalar
  740. # We need to also verify that (_maybe_get_const(size, "t").dim() == 0)
  741. # but this information is not always available. Try to get the dim,
  742. # and if not assume that it is not a scalar.
  743. try:
  744. is_scalar = not _is_packed_list(size) and (
  745. (_maybe_get_const(size, "t").dim() == 0)
  746. )
  747. except AttributeError:
  748. is_scalar = not _is_packed_list(size)
  749. if not is_scalar:
  750. warnings.warn(
  751. "Cannot verify if the output_size is a scalar "
  752. "while exporting interpolate. Assuming that it is not a scalar."
  753. )
  754. if is_scalar:
  755. rank = _get_tensor_rank(input)
  756. if rank is None:
  757. return _unimplemented(
  758. "interpolate (with a scalar output_size)",
  759. "missing input shape (try giving an array of output_size values)",
  760. )
  761. size = _unsqueeze_helper(g, size, [0])
  762. size = [size for i in range(rank - 2)]
  763. size = g.op("Concat", *size, axis_i=0)
  764. size = g.op("Cast", size, to_i=cast_pytorch_to_onnx["Long"])
  765. size = g.op("Concat", input_size, size, axis_i=0)
  766. if GLOBALS.export_onnx_opset_version >= 13:
  767. empty_roi = _optional_input_placeholder_tensor(g)
  768. empty_scales = _optional_input_placeholder_tensor(g)
  769. else:
  770. empty_roi = g.op("Constant", value_t=torch.tensor([], dtype=torch.float32))
  771. empty_scales = g.op(
  772. "Constant", value_t=torch.tensor([], dtype=torch.float32)
  773. )
  774. return g.op(
  775. "Resize",
  776. input,
  777. empty_roi,
  778. empty_scales,
  779. size,
  780. coordinate_transformation_mode_s=coordinate_transformation_mode,
  781. cubic_coeff_a_f=-0.75, # only valid when mode="cubic"
  782. mode_s=mode, # nearest, linear, or cubic
  783. nearest_mode_s="floor",
  784. )
  785. else: # if not _is_none(scales)
  786. rank = _get_tensor_rank(input)
  787. if rank is None:
  788. return _unimplemented("interpolate (with scales)", "missing input shape")
  789. if GLOBALS.export_onnx_opset_version >= 13:
  790. empty_roi = _optional_input_placeholder_tensor(g)
  791. else:
  792. empty_roi = g.op("Constant", value_t=torch.tensor([], dtype=torch.float32))
  793. scales = _interpolate_get_scales(g, scale_factor, rank)
  794. return g.op(
  795. "Resize",
  796. input,
  797. empty_roi,
  798. scales,
  799. coordinate_transformation_mode_s=coordinate_transformation_mode,
  800. cubic_coeff_a_f=-0.75, # only valid when mode="cubic"
  801. mode_s=mode, # nearest, linear, or cubic
  802. nearest_mode_s="floor",
  803. ) # only valid when mode="nearest"
  804. def _unbind_helper(g, self, dim, _outputs):
  805. if GLOBALS.export_onnx_opset_version < 11:
  806. from torch.onnx.symbolic_opset9 import unbind
  807. elif GLOBALS.export_onnx_opset_version <= 12:
  808. from torch.onnx.symbolic_opset11 import unbind # type: ignore[no-redef]
  809. else:
  810. from torch.onnx.symbolic_opset13 import unbind # type: ignore[no-redef]
  811. return unbind(g, self, dim, _outputs)
  812. def _scatter_helper(g, self, dim, index, src):
  813. if GLOBALS.export_onnx_opset_version <= 10:
  814. from torch.onnx.symbolic_opset9 import scatter
  815. else:
  816. # for mypy, scatter was imported two lines above
  817. from torch.onnx.symbolic_opset11 import scatter # type: ignore[no-redef]
  818. return scatter(g, self, dim, index, src)
  819. def _repeat_interleave_split_helper(g, self, reps, dim):
  820. if GLOBALS.export_onnx_opset_version <= 12:
  821. split_out = g.op("Split", self, split_i=[1] * reps, axis_i=dim, outputs=reps)
  822. else:
  823. from torch.onnx.symbolic_opset13 import split
  824. repeats = g.op("Constant", value_t=torch.tensor([1] * reps))
  825. split_out = split(g, self, repeats, dim, _outputs=reps)
  826. return split_out if reps > 1 else [split_out]
  827. def _arange_cast_helper(g, end, start=None, step=None, dtype=None):
  828. def _is_all_integral(scalars):
  829. for scalar in scalars:
  830. try:
  831. if scalar.type().scalarType() != "Long":
  832. return False
  833. except Exception:
  834. pass
  835. return True
  836. # This logic is based on torch.arange docs. If "dtype" is provided,
  837. # infer input types from dtype. If not, then check if any of start, stop,
  838. # or step are floating point, and infer the type from get_default.
  839. # Otherwise, the dtype is inferred to be torch.int64.
  840. if dtype is None or (_is_value(dtype) and _is_none(dtype)):
  841. if _is_all_integral([start, end, step]):
  842. type = scalar_type_to_pytorch_type.index(torch.int64)
  843. else:
  844. type = scalar_type_to_pytorch_type.index(torch.get_default_dtype())
  845. else:
  846. type = dtype
  847. start = g.op("Cast", start, to_i=scalar_type_to_onnx[type]) if start else None
  848. end = g.op("Cast", end, to_i=scalar_type_to_onnx[type]) if end else None
  849. step = g.op("Cast", step, to_i=scalar_type_to_onnx[type]) if step else None
  850. return type, end, start, step
  851. def _arange_helper(g, *args):
  852. if GLOBALS.export_onnx_opset_version <= 10:
  853. from torch.onnx.symbolic_opset9 import arange
  854. else:
  855. from torch.onnx.symbolic_opset11 import arange # type: ignore[no-redef]
  856. return arange(g, *args)
  857. def _size_helper(g, self, dim):
  858. full_shape = g.op("Shape", self)
  859. from torch.onnx.symbolic_opset9 import select
  860. return select(g, full_shape, g.op("Constant", value_t=torch.tensor([0])), dim)
  861. def _index_fill_reshape_helper(g, self, dim, index):
  862. # 1. reshape index => [1, ..., 1, dim, 1, ..., 1]
  863. # 2. expand index => [..., dim, ...], same shape as self except for dim.
  864. # 3. expand value as well.
  865. # 4. apply onnx::scatter.
  866. from torch.onnx.symbolic_opset9 import expand
  867. if GLOBALS.export_onnx_opset_version <= 10:
  868. from torch.onnx.symbolic_opset9 import scatter
  869. else:
  870. # for mypy, scatter was imported two lines above
  871. from torch.onnx.symbolic_opset11 import scatter # type: ignore[no-redef]
  872. if self.type().dim() is None:
  873. return _unimplemented("index_fill", "input rank not accesible")
  874. self_dim = self.type().dim()
  875. dim_value = _parse_arg(dim, "i")
  876. unsqueezed_index = _unsqueeze_helper(
  877. g, index, [i for i in range(self_dim) if i != dim_value]
  878. )
  879. expanded_index_shape = scatter(
  880. g, g.op("Shape", self), 0, _unsqueeze_helper(g, dim, [0]), g.op("Shape", index)
  881. )
  882. expanded_index = expand(g, unsqueezed_index, expanded_index_shape, None)
  883. return expanded_index_shape, expanded_index
  884. # By default, when any value in the 'shape' input is equal to zero
  885. # the corresponding dimension value is copied from the input tensor dynamically.
  886. # allowzero=1 indicates that if any value in the 'shape' input is set to zero,
  887. # the zero value is honored, similar to NumPy.
  888. # allowzero=1 is only supported for opset version >= 14.
  889. def _reshape_helper(g, input, shape, allowzero=0):
  890. shape = _maybe_get_const(shape, "is")
  891. if not _is_value(shape):
  892. shape = g.op("Constant", value_t=torch.LongTensor(shape))
  893. if GLOBALS.export_onnx_opset_version <= 13:
  894. if allowzero == 1:
  895. raise _onnx_opset_unsupported(
  896. "Reshape with allowzero=1", GLOBALS.export_onnx_opset_version, 14
  897. )
  898. return g.op("Reshape", input, shape)
  899. else:
  900. return g.op("Reshape", input, shape, allowzero_i=allowzero)
  901. def _batchnorm_helper(g, input, weight, bias, running_mean, running_var):
  902. from torch.onnx.symbolic_opset9 import _var_mean
  903. batch_size = _get_tensor_dim_size(input, 0)
  904. channel_size = _get_tensor_dim_size(input, 1)
  905. if weight is None or _is_none(weight):
  906. if channel_size is None:
  907. raise RuntimeError(
  908. "Unsupported: ONNX export of batch_norm for unknown " "channel size."
  909. )
  910. weight_value = torch.tensor([1.0] * channel_size).type(
  911. "torch." + input.type().scalarType() + "Tensor"
  912. )
  913. weight = g.op("Constant", value_t=weight_value)
  914. if bias is None or _is_none(bias):
  915. if channel_size is None:
  916. raise RuntimeError(
  917. "Unsupported: ONNX export of batch_norm for unknown " "channel size."
  918. )
  919. bias_value = torch.tensor([0.0] * channel_size).type(
  920. "torch." + input.type().scalarType() + "Tensor"
  921. )
  922. bias = g.op("Constant", value_t=bias_value)
  923. # If track_running_stats is set to False batch statistics are instead used during evaluation time
  924. if (
  925. running_mean is None
  926. or _is_none(running_mean)
  927. or running_var is None
  928. or _is_none(running_var)
  929. ):
  930. assert batch_size is not None and channel_size is not None
  931. reshape_in = _reshape_helper(
  932. g,
  933. input,
  934. g.op(
  935. "Constant",
  936. value_t=torch.tensor([batch_size, channel_size, -1], dtype=torch.int64),
  937. ),
  938. )
  939. trans_in = g.op("Transpose", reshape_in, perm_i=[0, 2, 1])
  940. running_var, running_mean = _var_mean(
  941. g,
  942. trans_in,
  943. g.op("Constant", value_t=torch.tensor([0, 1], dtype=torch.int64)),
  944. False,
  945. False,
  946. )
  947. return weight, bias, running_mean, running_var
  948. def _avgpool_helper(
  949. tuple_fn: Callable[[Any], Sequence[int]],
  950. padding: Union[int, Sequence[int]],
  951. kernel_size,
  952. stride,
  953. divisor_override,
  954. name,
  955. ) -> Tuple[int, ...]:
  956. if divisor_override and divisor_override.node().kind() != "prim::Constant":
  957. _unimplemented(name, "divisor_override")
  958. return tuple(tuple_fn(padding))
  959. def check_training_mode(op_train_mode, op_name):
  960. op_train_mode = True if op_train_mode == 1 else False
  961. if GLOBALS.training_mode is not None and op_train_mode != GLOBALS.training_mode:
  962. op_mode = "training " if op_train_mode else "inference"
  963. training_mode = "training " if GLOBALS.training_mode else "inference"
  964. # setting the model mode could result in op_mode != _flags.training_mode
  965. # if the model is a FuncModule. In this case we warn the user of
  966. # the state and export depending on op_mode
  967. # This is to support use-cases of fixing certain layer weights
  968. # in training.
  969. warnings.warn(
  970. "ONNX export mode is set to "
  971. + training_mode
  972. + " mode, but operator "
  973. + op_name
  974. + " is set to "
  975. + op_mode
  976. + " mode. The operators will be exported in "
  977. + op_mode
  978. + ", as specified by the functional operator."
  979. )
  980. def _flatten_helper(g, input, start_dim, end_dim, dim):
  981. input_size = g.op("Shape", input)
  982. slice1 = _slice_helper(g, input_size, axes=[0], starts=[0], ends=[start_dim])
  983. slices = [slice1, g.op("Constant", value_t=torch.tensor([-1], dtype=torch.long))]
  984. if end_dim < dim - 1:
  985. slice3 = _slice_helper(
  986. g, input_size, axes=[0], starts=[end_dim + 1], ends=[dim]
  987. )
  988. slices = [
  989. slice1,
  990. g.op("Constant", value_t=torch.tensor([-1], dtype=torch.long)),
  991. slice3,
  992. ]
  993. final_shape = g.op("Concat", *slices, axis_i=0)
  994. from torch.onnx.symbolic_opset9 import _reshape_from_tensor
  995. return _reshape_from_tensor(g, input, final_shape)
  996. def _is_split_static(split_size_or_sizes, _outputs):
  997. if _outputs is None:
  998. return False
  999. if (
  1000. _is_value(split_size_or_sizes)
  1001. and split_size_or_sizes.node().kind() != "onnx::Constant"
  1002. ):
  1003. return False
  1004. return True
  1005. def _optional_input_placeholder_tensor(g):
  1006. n = g.op("prim::Constant")
  1007. n.setType(_C.OptionalType.ofTensor())
  1008. return n
  1009. def _handle_reduce_dim_none(g, self, op_name):
  1010. rank = _get_tensor_rank(self)
  1011. if rank is not None and any(
  1012. [_get_tensor_dim_size(self, i) == 0 for i in range(rank)]
  1013. ):
  1014. # If input tensor is empty, according to ONNX ReduceSum definition,
  1015. # set keepdims=1 so that the resulted tensor has the same rank as the input.
  1016. return g.op(op_name, self, keepdims_i=1)
  1017. return g.op(op_name, self, keepdims_i=0)
  1018. def dequantize_helper(
  1019. g,
  1020. qtensor: _C.Value,
  1021. qdtype: Optional[torch.onnx.TensorProtoDataType] = None,
  1022. ) -> Tuple[_C.Value, _C.Value, _C.Value, Optional[_C.Value]]:
  1023. """Appends to graph `g` ONNX nodes that dequantizes `qtensor` into `tensor`.
  1024. Args:
  1025. g: Graph, the ONNX IR graph that is under construction.
  1026. qtensor: torch._C.Value, either a tuple of (quantized_tensor, scale, zero_point) for per tensor quantization,
  1027. or (quantized_tensor, scale, zero_point, axis) for per channel quantization.
  1028. Representing the quantized tensor.
  1029. qdtype: torch.onnx.TensorProtoDataType default None, if not None, represents the data type of quantized tensor.
  1030. It must be either torch.onnx.TensorProtoDataType.UINT8 or torch.onnx.TensorProtoDataType.INT8.
  1031. """
  1032. unpacked_qtensors = _unpack_tuple(qtensor)
  1033. tensor, scale, zero_point = unpacked_qtensors[:3]
  1034. axis = unpacked_qtensors[3] if len(unpacked_qtensors) >= 4 else None
  1035. axis_i = _get_const(axis, "i", "axis")
  1036. input_qdtype = cast_pytorch_to_onnx[tensor.type().scalarType()]
  1037. if qdtype is None:
  1038. if input_qdtype is not None:
  1039. qdtype = input_qdtype
  1040. else:
  1041. qdtype = _C_onnx.TensorProtoDataType.UINT8
  1042. value = g.op("Cast", tensor, to_i=qdtype)
  1043. scale = g.op("Cast", scale, to_i=_C_onnx.TensorProtoDataType.FLOAT)
  1044. zero_point = g.op("Cast", zero_point, to_i=qdtype)
  1045. if axis_i is not None and GLOBALS.export_onnx_opset_version < 13:
  1046. _onnx_opset_unsupported_detailed(
  1047. "DequantizeLinear",
  1048. GLOBALS.export_onnx_opset_version,
  1049. 13,
  1050. "Attribute axis is not supported.",
  1051. )
  1052. return (
  1053. g.op("DequantizeLinear", value, scale, zero_point, axis_i=axis_i),
  1054. scale,
  1055. zero_point,
  1056. axis,
  1057. )
  1058. def quantize_helper(
  1059. g,
  1060. tensor: _C.Value,
  1061. scale: _C.Value,
  1062. zero_point: _C.Value,
  1063. axis: Optional[_C.Value] = None,
  1064. ) -> _C.Value:
  1065. """Appends to graph `g` ONNX nodes that quantizes `tensor` based on `scale`, `zero_point` and `axis`.
  1066. Args:
  1067. g: Graph, the ONNX IR graph that is under construction.
  1068. tensor: torch._C.Value, representing the tensor to be quantized.
  1069. scale: torch._C.Value, quantized scale.
  1070. zero_point: torch._C.Value, quantized zero point.
  1071. axis: Optional[torch._C.Value] default None, if None, represents per tensor quantization.
  1072. Otherwise, represents per channel quantization, along given axis.
  1073. """
  1074. if (
  1075. axis is not None
  1076. and not _is_none(axis)
  1077. and GLOBALS.export_onnx_opset_version < 13
  1078. ):
  1079. _onnx_opset_unsupported_detailed(
  1080. "QuantizeLinear",
  1081. GLOBALS.export_onnx_opset_version,
  1082. 13,
  1083. "Attribute axis is not supported.",
  1084. )
  1085. assert scale is not None
  1086. if scale.type().scalarType() != "Float": # type: ignore[attr-defined]
  1087. # TODO(justinchuby): Remove type ignore after #81112 is checked in.
  1088. scale = g.op("Cast", scale, to_i=_C_onnx.TensorProtoDataType.FLOAT)
  1089. assert zero_point is not None
  1090. if zero_point.type().scalarType() not in ("Byte", "Char"): # type: ignore[attr-defined]
  1091. # TODO(justinchuby): Remove type ignore after #81112 is checked in.
  1092. zero_point = g.op("Cast", zero_point, to_i=_C_onnx.TensorProtoDataType.UINT8)
  1093. output = g.op(
  1094. "QuantizeLinear",
  1095. tensor,
  1096. scale,
  1097. zero_point,
  1098. axis_i=_get_const(axis, "i", "axis"),
  1099. )
  1100. args = [output, scale, zero_point]
  1101. if axis is not None and not _is_none(axis):
  1102. args.append(axis)
  1103. return g.op("prim::TupleConstruct", *args)
  1104. def requantize_bias_helper(g, bias, input_scale, weight_scale, axis=None):
  1105. """In PyTorch, bias is float and is quantized to int32 implicitly inside the quantized ATen op kernel.
  1106. In ONNX we need to make the quantization explicit because operators expect all of their inputs to be quantized.
  1107. Since int32 is not a supported output type by ONNX operator `QuantizeLinear`, quantization is exported using
  1108. regular operators.
  1109. """
  1110. bias_scale = g.op("Mul", weight_scale, input_scale)
  1111. bias_scale_shape = g.op("Shape", bias_scale)
  1112. bias_zero_point = g.op(
  1113. "ConstantOfShape", bias_scale_shape, value_t=torch.tensor([0], dtype=torch.int)
  1114. )
  1115. q_bias = g.op(
  1116. "Cast", g.op("Div", bias, bias_scale), to_i=_C_onnx.TensorProtoDataType.INT32
  1117. )
  1118. axis_args = []
  1119. if axis is not None and not _is_none(axis):
  1120. axis_args.append(axis)
  1121. return g.op("prim::TupleConstruct", q_bias, bias_scale, bias_zero_point, *axis_args)
  1122. def args_have_same_dtype(args):
  1123. assert args
  1124. base_dtype = args[0].type().scalarType()
  1125. has_same_dtype = all(elem.type().scalarType() == base_dtype for elem in args)
  1126. return has_same_dtype
  1127. # TODO(justinchuby): Delete these setters, users should set the vars directly.
  1128. def _set_opset_version(opset_version: int):
  1129. GLOBALS.export_onnx_opset_version = opset_version
  1130. def _set_operator_export_type(operator_export_type):
  1131. GLOBALS.operator_export_type = operator_export_type
  1132. def _set_training_mode(training_mode):
  1133. GLOBALS.training_mode = training_mode
  1134. # This function is for debug use only.
  1135. # onnx_shape_inference = False by default.
  1136. def _set_onnx_shape_inference(onnx_shape_inference: bool):
  1137. GLOBALS.onnx_shape_inference = onnx_shape_inference
  1138. # Metaprogram symbolics for each ATen native specialized cast operator.
  1139. # For e.g. we specify a function named `_cast_uint8_t` that instantiates an
  1140. # ONNX cast node with `to` attribute "UINT8"
  1141. #
  1142. # TODO: remove these once we support Type's in the JIT IR and we can once again
  1143. # use the unified toType operator
  1144. cast_pytorch_to_onnx = {
  1145. "Byte": _C_onnx.TensorProtoDataType.UINT8,
  1146. "Char": _C_onnx.TensorProtoDataType.INT8,
  1147. "Double": _C_onnx.TensorProtoDataType.DOUBLE,
  1148. "Float": _C_onnx.TensorProtoDataType.FLOAT,
  1149. "Half": _C_onnx.TensorProtoDataType.FLOAT16,
  1150. "Int": _C_onnx.TensorProtoDataType.INT32,
  1151. "Long": _C_onnx.TensorProtoDataType.INT64,
  1152. "Short": _C_onnx.TensorProtoDataType.INT16,
  1153. "Bool": _C_onnx.TensorProtoDataType.BOOL,
  1154. "ComplexFloat": _C_onnx.TensorProtoDataType.COMPLEX64,
  1155. "ComplexDouble": _C_onnx.TensorProtoDataType.COMPLEX128,
  1156. "BFloat16": _C_onnx.TensorProtoDataType.BFLOAT16,
  1157. "Undefined": _C_onnx.TensorProtoDataType.UNDEFINED,
  1158. }
  1159. scalar_name_to_pytorch = {
  1160. "uint8_t": "Byte",
  1161. "int8_t": "Char",
  1162. "double": "Double",
  1163. "float": "Float",
  1164. "half": "Half",
  1165. "int": "Int",
  1166. "int64_t": "Long",
  1167. "int16_t": "Short",
  1168. "bool": "Bool",
  1169. "complex64": "ComplexFloat",
  1170. "complex128": "ComplexDouble",
  1171. "qint8": "QInt8",
  1172. "quint8": "QUInt8",
  1173. "qint32": "QInt32",
  1174. "bfloat16": "BFloat16",
  1175. }
  1176. class ScalarType(enum.IntEnum):
  1177. """A human-readable name for a key into scalar_type_to_pytorch_type."""
  1178. UINT8 = 0
  1179. INT8 = enum.auto()
  1180. SHORT = enum.auto()
  1181. INT = enum.auto()
  1182. INT64 = enum.auto()
  1183. HALF = enum.auto()
  1184. FLOAT = enum.auto()
  1185. DOUBLE = enum.auto()
  1186. COMPLEX32 = enum.auto()
  1187. COMPLEX64 = enum.auto()
  1188. COMPLEX128 = enum.auto()
  1189. BOOL = enum.auto()
  1190. QINT8 = enum.auto()
  1191. QUINT8 = enum.auto()
  1192. QINT32 = enum.auto()
  1193. BFLOAT16 = enum.auto()
  1194. # This indicates each scalar type's corresponding
  1195. # torch type. Related source:
  1196. # https://github.com/pytorch/pytorch/blob/344defc9733a45fee8d0c4d3f5530f631e823196/c10/core/ScalarType.h
  1197. scalar_type_to_pytorch_type = [
  1198. torch.uint8, # 0
  1199. torch.int8, # 1
  1200. torch.short, # 2
  1201. torch.int, # 3
  1202. torch.int64, # 4
  1203. torch.half, # 5
  1204. torch.float, # 6
  1205. torch.double, # 7
  1206. torch.complex32, # 8
  1207. torch.complex64, # 9
  1208. torch.complex128, # 10
  1209. torch.bool, # 11
  1210. torch.qint8, # 12
  1211. torch.quint8, # 13
  1212. torch.qint32, # 14
  1213. torch.bfloat16, # 15
  1214. ]
  1215. # source of truth is
  1216. # https://github.com/pytorch/pytorch/blob/master/torch/csrc/utils/tensor_dtypes.cpp
  1217. pytorch_name_to_type = {
  1218. "Byte": torch.uint8,
  1219. "Char": torch.int8,
  1220. "Double": torch.double,
  1221. "Float": torch.float,
  1222. "Half": torch.half,
  1223. "Int": torch.int,
  1224. "Long": torch.int64,
  1225. "Short": torch.short,
  1226. "Bool": torch.bool,
  1227. "ComplexFloat": torch.complex64,
  1228. "ComplexDouble": torch.complex128,
  1229. "QInt8": torch.qint8,
  1230. "QUInt8": torch.quint8,
  1231. "QInt32": torch.qint32,
  1232. "BFloat16": torch.bfloat16,
  1233. }
  1234. def _cast_func_template(to_i, g, input, non_blocking):
  1235. return g.op("Cast", input, to_i=to_i)
  1236. scalar_type_to_onnx = [
  1237. cast_pytorch_to_onnx["Byte"], # 0
  1238. cast_pytorch_to_onnx["Char"], # 1
  1239. cast_pytorch_to_onnx["Short"], # 2
  1240. cast_pytorch_to_onnx["Int"], # 3
  1241. cast_pytorch_to_onnx["Long"], # 4
  1242. cast_pytorch_to_onnx["Half"], # 5
  1243. cast_pytorch_to_onnx["Float"], # 6
  1244. cast_pytorch_to_onnx["Double"], # 7
  1245. cast_pytorch_to_onnx["Undefined"], # 8
  1246. cast_pytorch_to_onnx["ComplexFloat"], # 9
  1247. cast_pytorch_to_onnx["ComplexDouble"], # 10
  1248. cast_pytorch_to_onnx["Bool"], # 11
  1249. cast_pytorch_to_onnx["Char"], # 12
  1250. cast_pytorch_to_onnx["Byte"], # 13
  1251. cast_pytorch_to_onnx["Int"], # 14
  1252. cast_pytorch_to_onnx["BFloat16"], # 15
  1253. ]
  1254. # Global set to store the list of quantized operators in the network.
  1255. # This is currently only used in the conversion of quantized ops from PT -> C2 via ONNX.
  1256. _quantized_ops: Set[int] = set()