dynamic_shapes.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. # mypy: allow-untyped-defs
  2. import dataclasses
  3. import inspect
  4. import logging
  5. import sys
  6. from collections import defaultdict
  7. from collections.abc import Callable
  8. from enum import auto, Enum
  9. from typing import Any, TYPE_CHECKING, Union
  10. import torch
  11. from torch.utils._pytree import (
  12. _get_node_type,
  13. BUILTIN_TYPES,
  14. KeyPath,
  15. keystr,
  16. MappingKey,
  17. SequenceKey,
  18. SUPPORTED_NODES,
  19. tree_iter,
  20. tree_map,
  21. tree_map_with_path,
  22. tree_structure,
  23. TreeSpec,
  24. )
  25. from .exported_program import ExportedProgram
  26. if TYPE_CHECKING:
  27. from sympy import Symbol
  28. from torch._guards import Source
  29. from torch.fx.experimental.symbolic_shapes import ShapeEnv, StrictMinMaxConstraint
  30. __all__ = [
  31. "Constraint",
  32. "Dim",
  33. "dims",
  34. "refine_dynamic_shapes_from_suggested_fixes",
  35. "AdditionalInputs",
  36. ]
  37. log = logging.getLogger(__name__)
  38. class _DimHintType(Enum):
  39. """
  40. Enum for dynamic shape hints.
  41. - AUTO means automatic inference of shape (static or dynamic).
  42. - STATIC means static shape (always specialized).
  43. - DYNAMIC means dynamic, will error out if specialized.
  44. """
  45. AUTO = auto()
  46. STATIC = auto()
  47. DYNAMIC = auto()
  48. @dataclasses.dataclass
  49. class _DimHint:
  50. """
  51. Internal class for dynamic shape hints.
  52. - min and max are optional.
  53. - _factory is for UX only, below example:
  54. auto_hint = _DimHint.AUTO() # _factory=True
  55. bounded_hint = auto_hint(min=10, max=100) # Returns new instance with _factory=False
  56. bounded_hint(min=5, max=50) # Will fail, non-factory instance cannot be called
  57. """
  58. type: _DimHintType
  59. min: int | None = None
  60. max: int | None = None
  61. _factory: bool | None = True
  62. @staticmethod
  63. def AUTO():
  64. return _DimHint(_DimHintType.AUTO)
  65. @staticmethod
  66. def DYNAMIC():
  67. return _DimHint(_DimHintType.DYNAMIC)
  68. @staticmethod
  69. def STATIC():
  70. return _DimHint(_DimHintType.STATIC)
  71. def __call__(self, min=None, max=None) -> "_DimHint":
  72. if not self._factory:
  73. raise TypeError(f"'{type(self)}' object is not callable")
  74. if min is not None and min < 0:
  75. raise AssertionError(f"min must be non-negative, got {min}")
  76. if max is not None and max < 0:
  77. raise AssertionError(f"max must be non-negative, got {max}")
  78. if min is not None and max is not None and min > max:
  79. raise AssertionError(f"min must be <= max, got min={min}, max={max}")
  80. return _DimHint(self.type, min=min, max=max, _factory=False)
  81. def __repr__(self):
  82. parts = [self.type.name]
  83. if self.min is not None:
  84. parts.append(f"min={self.min}")
  85. if self.max is not None:
  86. parts.append(f"max={self.max}")
  87. return f"DimHint({', '.join(parts)})"
  88. class Dim:
  89. """
  90. The ``Dim`` class allows users to specify dynamism in their exported
  91. programs. By marking a dimension with a ``Dim``, the compiler associates the
  92. dimension with a symbolic integer containing a dynamic range.
  93. The API can be used in 2 ways: Dim hints (i.e. automatic dynamic shapes:
  94. ``Dim.AUTO``, ``Dim.DYNAMIC``, ``Dim.STATIC``), or named Dims (i.e.
  95. ``Dim("name", min=1, max=2)``).
  96. Dim hints provide the lowest barrier to exportability, with the user only
  97. needing to specify if a dimension if dynamic, static, or left for the
  98. compiler to decide (``Dim.AUTO``). The export process will automatically
  99. infer the remaining constraints on min/max ranges and relationships between
  100. dimensions.
  101. Example::
  102. class Foo(nn.Module):
  103. def forward(self, x, y):
  104. assert x.shape[0] == 4
  105. assert y.shape[0] >= 16
  106. return x @ y
  107. x = torch.randn(4, 8)
  108. y = torch.randn(8, 16)
  109. dynamic_shapes = {
  110. "x": {0: Dim.AUTO, 1: Dim.AUTO},
  111. "y": {0: Dim.AUTO, 1: Dim.AUTO},
  112. }
  113. ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)
  114. Here, export would raise an exception if we replaced all uses of ``Dim.AUTO`` with ``Dim.DYNAMIC``,
  115. as ``x.shape[0]`` is constrained to be static by the model.
  116. More complex relations between dimensions may also be codegened as runtime assertion nodes by the compiler,
  117. e.g. ``(x.shape[0] + y.shape[1]) % 4 == 0``, to be raised if runtime inputs do not satisfy such constraints.
  118. You may also specify min-max bounds for Dim hints, e.g. ``Dim.AUTO(min=16, max=32)``, ``Dim.DYNAMIC(max=64)``,
  119. with the compiler inferring the remaining constraints within the ranges. An exception will be raised if
  120. the valid range is entirely outside the user-specified range.
  121. Named Dims provide a stricter way of specifying dynamism, where exceptions are raised if the compiler
  122. infers constraints that do not match the user specification. For example, exporting the previous
  123. model, the user would need the following ``dynamic_shapes`` argument::
  124. s0 = Dim("s0")
  125. s1 = Dim("s1", min=16)
  126. dynamic_shapes = {
  127. "x": {0: 4, 1: s0},
  128. "y": {0: s0, 1: s1},
  129. }
  130. ep = torch.export(Foo(), (x, y), dynamic_shapes=dynamic_shapes)
  131. Named Dims also allow specification of relationships between dimensions, up
  132. to univariate linear relations. For example, the following indicates one
  133. dimension is a multiple of another plus 4::
  134. s0 = Dim("s0")
  135. s1 = 3 * s0 + 4
  136. """
  137. AUTO = _DimHint.AUTO()
  138. DYNAMIC = _DimHint.DYNAMIC()
  139. STATIC = _DimHint.STATIC()
  140. def __init__(self, name: str, *, min: int | None = None, max: int | None = None):
  141. from torch.utils._sympy.numbers import int_oo
  142. _min = 0 if min is None else min
  143. _max = int_oo if max is None else max
  144. if not (_max > _min):
  145. raise AssertionError(
  146. f"Cannot create Dim with inconsistent min={min}, max={max}"
  147. )
  148. if not name.isidentifier():
  149. raise AssertionError(f"Dim name must be a valid identifier, got {name}")
  150. self.__name__ = name
  151. self.min = _min
  152. self.max = _max
  153. def __add__(self, other) -> "Dim":
  154. # e.g., dim + 1
  155. if type(other) is not int:
  156. raise NotImplementedError(
  157. f"Attempted to add {other} to {self.__name__}, where an integer was expected. "
  158. "(Only increasing linear operations with integer coefficients are supported.)"
  159. )
  160. return self._derive(lambda x: x + other)
  161. def __radd__(self, other) -> "Dim":
  162. return self + other
  163. def __sub__(self, other) -> "Dim":
  164. # e.g., dim - 1
  165. if type(other) is not int:
  166. raise NotImplementedError(
  167. f"Attempted to subtract {other} from {self.__name__}, where an integer was expected. "
  168. "(Only increasing linear operations with integer coefficients are supported.)"
  169. )
  170. return self._derive(lambda x: x - other)
  171. def __rsub__(self, other) -> "Dim":
  172. raise NotImplementedError(
  173. f"Attempted to negate {self.__name__}. "
  174. "(Only increasing linear operations with integer coefficients are supported.)"
  175. )
  176. def __mul__(self, other) -> "Dim":
  177. # e.g., dim * 2
  178. if type(other) is not int or other <= 0:
  179. raise NotImplementedError(
  180. f"Attempted to multiply {other} with {self.__name__}, where a positive integer was expected. "
  181. "(Only increasing linear operations with integer coefficients are supported.)"
  182. )
  183. return self._derive(lambda x: x * other)
  184. def __rmul__(self, other) -> "Dim":
  185. return self * other
  186. def _derived_name(self, fn) -> str:
  187. from sympy import sympify
  188. return str(fn(sympify(self.__name__)))
  189. def _derive(self, fn) -> "Dim":
  190. return _DerivedDim(self._derived_name(fn), self, fn)
  191. @staticmethod
  192. def _readable(name: str, min_: int, max_: int) -> str:
  193. from torch.utils._sympy.numbers import int_oo
  194. if min_ == 2:
  195. min_ = None # type: ignore[assignment]
  196. if max_ == int_oo:
  197. max_ = None # type: ignore[assignment]
  198. if min_ is None and max_ is None:
  199. return f"Dim('{name}')"
  200. if min_ is None:
  201. return f"Dim('{name}', max={max_})"
  202. if max_ is None:
  203. return f"Dim('{name}', min={min_})"
  204. return f"Dim('{name}', min={min_}, max={max_})"
  205. def __repr__(self):
  206. return Dim._readable(self.__name__, self.min, self.max)
  207. _Dim = Dim # TODO(pianpwk): remove after it's no longer internally breaking
  208. class _StaticDim(Dim):
  209. """
  210. Class for static :func:`Dim` types.
  211. This class is only for setting and checking static dim constraints,
  212. and the user should never interact with it.
  213. """
  214. def __init__(self, value: int):
  215. self.__name__ = str(value)
  216. self.value = value
  217. @property
  218. def min(self): # type: ignore[override]
  219. return self.value # type: ignore[attr-defined]
  220. @property
  221. def max(self): # type: ignore[override]
  222. return self.value # type: ignore[attr-defined]
  223. class _DerivedDim(Dim):
  224. """
  225. Class for derived :func:`Dim` types.
  226. Currently we only support increasing linear expressions with integer coefficients.
  227. In other words, a derived Dim can always be written in the form Ax + B, where
  228. x is a regular Dim (i.e., non-derived Dim), A and B are integers, and A is positive.
  229. (In particular, the latter ensures that x < y => Ax + B < Ay + B.)
  230. These restrictions on the form of derived Dims makes the metatheory simpler: e.g.,
  231. it simplifies computing ranges for derived Dims, solving for underlying regular Dims,
  232. deciding equalities between derived Dims, and so on.
  233. The function lambda x: Ax + B is expressed by `fn`, where x is a normal Dim, `root`.
  234. The range of a derived Dim is computed by mapping `fn` over the range of its `root`.
  235. """
  236. def __init__(self, name: str, root: Dim, fn: Callable):
  237. self.__name__ = name
  238. self.root = root
  239. self.fn = fn
  240. @property
  241. def min(self): # type: ignore[override]
  242. # assume that self.fn is an increasing function
  243. # TODO(avik): use sympy value range analysis instead?
  244. from sympy import Integer
  245. from torch.utils._sympy.numbers import int_oo
  246. if self.root.min is -int_oo: # type: ignore[attr-defined]
  247. return -int_oo # fn not needed cuz increasing
  248. _min_symint = self.fn(Integer(self.root.min)) # type: ignore[attr-defined]
  249. root = self.root # type: ignore[attr-defined]
  250. if _min_symint < 0:
  251. raise AssertionError(
  252. f"Expected derived min value of {self.__name__} to be >= 0. "
  253. f"Please specify an appropriate min value for {root.__name__} "
  254. f"(currently {root.min})."
  255. )
  256. return int(_min_symint)
  257. @property
  258. def max(self): # type: ignore[override]
  259. # assume that self.fn is an increasing function
  260. # TODO(avik): use sympy value range analysis instead?
  261. from sympy import Integer
  262. from torch.utils._sympy.numbers import int_oo
  263. if self.root.max is int_oo: # type: ignore[attr-defined]
  264. return int_oo # fn not needed cuz increasing
  265. _max_symint = self.fn(Integer(self.root.max)) # type: ignore[attr-defined]
  266. root = self.root # type: ignore[attr-defined]
  267. if _max_symint > sys.maxsize - 1:
  268. raise AssertionError(
  269. f"Expected derived max value of {self.__name__} to be <= {sys.maxsize - 1}. "
  270. f"Please specify an appropriate max value for {root.__name__} "
  271. f"(currently {root.max})."
  272. )
  273. return int(_max_symint)
  274. def _derive(self, fn):
  275. # We support nesting, e.g., 2*dim + 1.
  276. # This is implemented by composing operations on the same root.
  277. # As a consequence, roots are always regular Dims (i.e., not derived Dims).
  278. return _DerivedDim(
  279. self._derived_name(fn),
  280. self.root,
  281. lambda x: fn(self.fn(x)),
  282. )
  283. def __repr__(self):
  284. return self.__name__
  285. def dims(
  286. *names: str, min: int | None = None, max: int | None = None
  287. ) -> tuple[Dim, ...]:
  288. """
  289. Util to create multiple :func:`Dim` types.
  290. Returns:
  291. A tuple of :func:`Dim` types.
  292. """
  293. return tuple(Dim(name, min=min, max=max) for name in names) # type: ignore[misc]
  294. @dataclasses.dataclass
  295. class _ConstraintTarget:
  296. """
  297. This represents input tensor dimensions.
  298. """
  299. t_id: int
  300. dim: int
  301. @dataclasses.dataclass
  302. class _Constraint(_ConstraintTarget):
  303. """
  304. This represents a Dim describing a constraint target.
  305. `name` is the name of the Dim.
  306. `constraint_range` contains the min/max bounds of the Dim.
  307. """
  308. name: str
  309. constraint_range: "StrictMinMaxConstraint"
  310. def _clone_with_range(self, lower=0, upper=None):
  311. # Import sympy locally
  312. from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint
  313. from torch.utils._sympy.numbers import int_oo
  314. from torch.utils._sympy.value_ranges import ValueRanges
  315. if upper is None:
  316. upper = int_oo
  317. constraint_range = StrictMinMaxConstraint(
  318. vr=self.constraint_range.vr & ValueRanges(lower=lower, upper=upper),
  319. warn_only=False,
  320. )
  321. return _Constraint(
  322. self.t_id,
  323. self.dim,
  324. self.name,
  325. constraint_range,
  326. )
  327. def __ge__(self, lower):
  328. return self._clone_with_range(lower=lower)
  329. def __gt__(self, lower):
  330. return self._clone_with_range(lower=lower + 1)
  331. def __le__(self, upper):
  332. return self._clone_with_range(upper=upper)
  333. def __lt__(self, upper):
  334. return self._clone_with_range(upper=upper - 1)
  335. def __bool__(self):
  336. # NOTE(avik): We do not support compound expressions like a <= x <= b.
  337. # This is because Python implicitly desugars them into bool(a <= x) and bool(x <= b),
  338. # and moreover, enforces that any overload of __bool__ must return True or False.
  339. # FWIW, sympy also raises TypeError in this case.
  340. raise TypeError(
  341. "Cannot determine truth value of _Constraint. "
  342. "If you are trying to combine _Constraint's with logical connectives, "
  343. "you can specify them separately instead."
  344. )
  345. @property
  346. def serializable_spec(self):
  347. # We need a serialization compatible format of the constraint so that it
  348. # can be savedin the graph module w/o breaking the module serialization.
  349. # The saved constraints will be used directly for the post-exporting pass
  350. # that converts constraints to runtime assertion. The saved constraints
  351. # will not be saved in the serialized module.
  352. # TODO: A better way is needed. Currently we use 't_id' to map the constraint,
  353. # which is not reliable
  354. return {
  355. "t_id": self.t_id,
  356. "dim": self.dim,
  357. "min": self.constraint_range.vr.lower,
  358. "max": self.constraint_range.vr.upper,
  359. }
  360. @dataclasses.dataclass
  361. class _PhantomRoot:
  362. """
  363. This represents the root of a derived Dim where the root does not directly
  364. specify the shape of any input dimension, but the derived Dim does.
  365. e.g., the input shapes 2*dim and dim + 1 are related via a "phantom" dim.
  366. The fields `name`, `constraint_range`, and `val` carried by a phantom root
  367. help create a symbol for it. Any derived dims with this phantom root are
  368. backed by expressions over this symbol.
  369. """
  370. name: str
  371. constraint_range: "StrictMinMaxConstraint"
  372. val: int
  373. @dataclasses.dataclass
  374. class _DerivedConstraint(_ConstraintTarget):
  375. """
  376. This represents a derived Dim, whose root is either a regular constraint target
  377. (which directly specifies the shape of some input dimension) or a phantom root
  378. (which does so indirectly).
  379. It can be thought of as a subclass of `_Constraint`, except that it does not
  380. support <, <=, >, >= operations.
  381. """
  382. name: str
  383. constraint_range: "StrictMinMaxConstraint"
  384. root: _ConstraintTarget | _PhantomRoot
  385. fn: Callable
  386. @property
  387. def serializable_spec(self):
  388. # same as _Constraint.serializable_spec
  389. return {
  390. "t_id": self.t_id,
  391. "dim": self.dim,
  392. "min": self.constraint_range.vr.lower,
  393. "max": self.constraint_range.vr.upper,
  394. }
  395. @dataclasses.dataclass
  396. class _RelaxedConstraint(_ConstraintTarget):
  397. """
  398. This represents a dim marked with Dim.AUTO/DYNAMIC (i.e. mark_dynamic() or maybe_mark_dynamic()),
  399. which leaves relations & min/max ranges for inference, instead of requiring explicit specification.
  400. The intention is for constraint violations to not be raised if produce_guards() finds equalities or
  401. relations between a _RelaxedConstraint and another type of _Constraint.
  402. """
  403. @property
  404. def serializable_spec(self):
  405. return {
  406. "t_id": self.t_id,
  407. "dim": self.dim,
  408. }
  409. Constraint = _Constraint | _DerivedConstraint | _RelaxedConstraint
  410. @dataclasses.dataclass
  411. class _IntWrapper:
  412. """
  413. Dummy wrapper class to wrap around integer inputs so that when we parse the
  414. dynamic_shapes structure, we can mark if any of the integers were marked as
  415. dynamic.
  416. """
  417. val: int
  418. # Disallow specifying dynamism
  419. dynamism: _DimHint | int | None = dataclasses.field(init=False, default=None)
  420. def _process_equalities(
  421. constraint: Constraint,
  422. get_sources: Callable[[int, int], list["Source"]],
  423. shape_env: "ShapeEnv",
  424. names: dict[str, tuple[int, int]],
  425. source_pairs: list[tuple["Source", "Source"]],
  426. derived_equalities: list[tuple["Source", Union["Source", "Symbol"], Callable]],
  427. phantom_symbols: dict[str, "Symbol"],
  428. relaxed_sources: set["Source"],
  429. ):
  430. """
  431. Updates `source_pairs`, `derived_equalities`, and `phantom_symbols` (which become
  432. fields of `EqualityConstraint`) based on a given input `constraint`.
  433. """
  434. sources = get_sources(constraint.t_id, constraint.dim)
  435. if not sources: # empty sources due to unused shapes
  436. return
  437. source, *other_sources = sources
  438. # When t.size()[dim] maps to src0, src1, ..., srcN, we add
  439. # constraints that make src0 "equal" to src1, ..., srcN.
  440. source_pairs.extend((source, other_source) for other_source in other_sources)
  441. if isinstance(constraint, _Constraint):
  442. if constraint.name in names:
  443. shared_t_id, shared_dim = names[constraint.name]
  444. other_sources = get_sources(shared_t_id, shared_dim)
  445. source_pairs.extend(
  446. (source, other_source) for other_source in other_sources
  447. )
  448. else:
  449. names[constraint.name] = (constraint.t_id, constraint.dim)
  450. elif isinstance(constraint, _DerivedConstraint):
  451. # branch based on the root of the _DerivedConstraint
  452. if not isinstance(constraint.root, _PhantomRoot):
  453. # either root points to an input source
  454. root = get_sources(constraint.root.t_id, constraint.root.dim)[0]
  455. else:
  456. # or root points to a phantom symbol
  457. if constraint.root.name in phantom_symbols:
  458. root = phantom_symbols[constraint.root.name]
  459. else:
  460. # create a phantom symbol in the shape env based on the _PhantomRoot
  461. root = shape_env.create_symbol(
  462. val=constraint.root.val,
  463. source=torch._dynamo.source.ConstantSource(constraint.root.name),
  464. dynamic_dim=torch.fx.experimental.symbolic_shapes.DimDynamic.DYNAMIC,
  465. constraint_dim=constraint.root.constraint_range,
  466. )
  467. phantom_symbols[constraint.root.name] = root
  468. fn = constraint.fn
  469. # A derived equality (source, root, fn) informally corresponds to source = fn(root).
  470. # Here source describes an input and root might describe another input or a phantom symbol.
  471. derived_equalities.append((source, root, fn))
  472. elif isinstance(constraint, _RelaxedConstraint):
  473. relaxed_sources.add(source)
  474. def _tree_map_with_path(
  475. func: Callable[..., Any],
  476. tree: Any,
  477. *dynamic_shapes: Any,
  478. tree_name: str | None = None,
  479. ) -> Any:
  480. """
  481. Customized tree_map for mapping pytrees to dynamic_shapes.
  482. For built-in types (e.g., standard collections) this behaves exactly like tree_map.
  483. OTOH for a user-defined class C registered with pytree, we cannot assume that a C
  484. containing tensors can be mapped to a C containing dynamic shapes (i.e., C may not
  485. be a polymorphic container). In that case we use the flattened form of C instead.
  486. Thus a C(**tensors) that flattens to (**tensors) will map to (**dynamic_shapes).
  487. Args:
  488. func: function to apply to each (int, float, str, bool, None, torch.Tensor)
  489. tree: input pytree
  490. dynamic_shapes: zero or more (typically one) dynamic_shapes to match
  491. Returns:
  492. output pytree mapping func to each (int, float, str, bool, None, torch.Tensor)
  493. """
  494. def is_leaf(t):
  495. # BUILTIN_TYPES is a subset of SUPPORTED_NODES, the latter being all types
  496. # registered with pytree. Types *not* in BUILTIN_TYPES include primitive types
  497. # (int, float, str, bool, None, torch.Tensor), which are not in SUPPORTED_NODES,
  498. # as well as user-defined classes registered with pytree, which are.
  499. return _get_node_type(t) not in BUILTIN_TYPES
  500. def f(path, t, *dynamic_shapes):
  501. typ = _get_node_type(t)
  502. # typ is not in BUILTIN_TYPES
  503. if typ in SUPPORTED_NODES:
  504. # thus typ is a user-defined class registered with pytree,
  505. # in which case flatten and recurse
  506. return tree_map_with_path(
  507. f,
  508. SUPPORTED_NODES[typ].flatten_fn(t)[0],
  509. *dynamic_shapes,
  510. is_leaf=is_leaf,
  511. )
  512. else:
  513. return func(path, t, *dynamic_shapes)
  514. try:
  515. return tree_map_with_path(f, tree, *dynamic_shapes, is_leaf=is_leaf)
  516. except ValueError as e:
  517. if "mismatch" in e.args[0]:
  518. # When PyTree finds a structural mismatch between tree and dynamic_shapes,
  519. # the error message is unfortunately quite horrible. Let's fix that.
  520. if not dynamic_shapes:
  521. raise AssertionError(
  522. "Cannot be a mismatch if there is no dynamic_shapes"
  523. ) from None
  524. if not tree_name:
  525. raise AssertionError(
  526. "Must provide a tree_name when there might be a mismatch"
  527. ) from None
  528. def _key(type_, context, i):
  529. # derive a PyTree key given the type, context, and child # of a TreeSpec
  530. if type_ is dict:
  531. return MappingKey(context[i])
  532. if type_ in (list, tuple):
  533. if context is not None:
  534. raise AssertionError(
  535. f"expected context to be None for type {type_}, got {context}"
  536. )
  537. return SequenceKey(i)
  538. raise AssertionError(f"Did not expect type {type_}")
  539. def raise_mismatch_error(msg):
  540. from torch._dynamo.exc import UserError, UserErrorType
  541. raise UserError(
  542. UserErrorType.INVALID_INPUT,
  543. f"Detected mismatch between the structure of `{tree_name}` and `dynamic_shapes`: {msg}",
  544. case_name="dynamic_shapes_validation",
  545. )
  546. def _compare(
  547. treespec: TreeSpec, other_treespec: TreeSpec, path: KeyPath
  548. ) -> None:
  549. # raise an error at the point where tree and dynamic_shapes differ,
  550. # including the path to that point and the reason for the difference
  551. rendered_path = keystr(path)
  552. if treespec.is_leaf():
  553. return
  554. if other_treespec.is_leaf():
  555. raise_mismatch_error(
  556. f"`{tree_name}{rendered_path}` is a {treespec.type}, "
  557. f"but `dynamic_shapes{rendered_path}` is not"
  558. )
  559. if treespec.type != other_treespec.type:
  560. raise_mismatch_error(
  561. f"`{tree_name}{rendered_path}` is a {treespec.type}, "
  562. f"but `dynamic_shapes{rendered_path}` is a {other_treespec.type}"
  563. )
  564. if treespec.num_children != other_treespec.num_children:
  565. raise_mismatch_error(
  566. f"`{tree_name}{rendered_path}` has {treespec.num_children} elements, "
  567. f"but `dynamic_shapes{rendered_path}` has {other_treespec.num_children} elements"
  568. )
  569. if treespec.type is dict:
  570. # context, children could be out of order
  571. if set(treespec.context) != set(other_treespec.context):
  572. raise_mismatch_error(
  573. f"`{tree_name}{rendered_path}` has keys {treespec.context}, "
  574. f"but `dynamic_shapes{rendered_path}` has keys {other_treespec.context}"
  575. )
  576. _remap = dict(
  577. zip(other_treespec.context, other_treespec.children())
  578. )
  579. other_children = [_remap[k] for k in treespec.context]
  580. else:
  581. other_children = other_treespec.children()
  582. for i, (child, other_child) in enumerate(
  583. zip(treespec.children(), other_children)
  584. ):
  585. _compare(
  586. child,
  587. other_child,
  588. path + (_key(treespec.type, treespec.context, i),),
  589. )
  590. treespec = tree_structure(tree, is_leaf=is_leaf)
  591. for other_tree in dynamic_shapes:
  592. other_treespec = tree_structure(other_tree, is_leaf)
  593. _compare(treespec, other_treespec, ())
  594. raise
  595. def _combine_args(f, args, kwargs) -> dict[str, Any]:
  596. # combine args and kwargs following the signature of f, as it happens
  597. # in the body of f when called with *args, **kwargs
  598. if isinstance(f, ExportedProgram):
  599. f = f.module()
  600. signature = (
  601. inspect.signature(f.forward)
  602. if isinstance(f, torch.nn.Module)
  603. else inspect.signature(f)
  604. )
  605. kwargs = kwargs if kwargs is not None else {}
  606. return signature.bind(*args, **kwargs).arguments
  607. class ShapesCollection:
  608. """
  609. Builder for dynamic_shapes.
  610. Used to assign dynamic shape specifications to tensors that appear in inputs.
  611. This is useful particularly when :func:`args` is a nested input structure, and it's
  612. easier to index the input tensors, than to replicate the structure of :func:`args` in
  613. the :func:`dynamic_shapes` specification.
  614. Example::
  615. args = {"x": tensor_x, "others": [tensor_y, tensor_z]}
  616. dim = torch.export.Dim(...)
  617. dynamic_shapes = torch.export.ShapesCollection()
  618. dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
  619. dynamic_shapes[tensor_y] = {0: dim * 2}
  620. # This is equivalent to the following (now auto-generated):
  621. # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [{0: dim * 2}, None]}
  622. torch.export(..., args, dynamic_shapes=dynamic_shapes)
  623. To specify dynamism for integers, we need to first wrap the integers using
  624. _IntWrapper so that we have a "unique identification tag" for each integer.
  625. Example::
  626. args = {"x": tensor_x, "others": [int_x, int_y]}
  627. # Wrap all ints with _IntWrapper
  628. mapped_args = pytree.tree_map_only(int, lambda a: _IntWrapper(a), args)
  629. dynamic_shapes = torch.export.ShapesCollection()
  630. dynamic_shapes[tensor_x] = (dim, dim + 1, 8)
  631. dynamic_shapes[mapped_args["others"][0]] = Dim.DYNAMIC
  632. # This is equivalent to the following (now auto-generated):
  633. # dynamic_shapes = {"x": (dim, dim + 1, 8), "others": [Dim.DYNAMIC, None]}
  634. torch.export(..., args, dynamic_shapes=dynamic_shapes)
  635. """
  636. def __init__(self):
  637. self._shapes = {}
  638. def __setitem__(self, t, shape):
  639. if not isinstance(t, (torch.Tensor, _IntWrapper)):
  640. raise AssertionError(
  641. f"Cannot assign shape to non-tensor or non-_IntWrapper type {type(t)}"
  642. )
  643. # TODO(avik): check that shape is indeed a Shape
  644. t_id = id(t)
  645. if t_id in self._shapes:
  646. _shape = self._shapes[t_id]
  647. if shape != _shape:
  648. raise AssertionError(
  649. f"Shapes assigned to input do not match: expected {_shape}, got {shape}"
  650. )
  651. else:
  652. self._shapes[id(t)] = shape
  653. def __getitem__(self, t):
  654. t_id = id(t)
  655. if t_id not in self._shapes:
  656. self._shapes[t_id] = {}
  657. return self._shapes[t_id]
  658. def __len__(self):
  659. return len(self._shapes)
  660. def dynamic_shapes(self, m, args, kwargs=None):
  661. """
  662. Generates the :func:`dynamic_shapes` pytree structure according to :func:`args` and :func:`kwargs`.
  663. """
  664. t_ids = set()
  665. def find_shape(path, t):
  666. t_id = id(t)
  667. if t_id in self._shapes:
  668. t_ids.add(t_id)
  669. return self._shapes[t_id]
  670. else:
  671. return None
  672. combined_args = _combine_args(m, args, kwargs)
  673. dynamic_shapes = _tree_map_with_path(find_shape, combined_args)
  674. if any(t_id not in t_ids for t_id in self._shapes):
  675. raise ValueError(
  676. "Some tensors that were assigned shapes were not found in args. "
  677. "Maybe such tensors were copied when passing them as args? "
  678. "Maybe such tensors are contained in classes that were not registered with pytree?"
  679. )
  680. return dynamic_shapes
  681. class AdditionalInputs:
  682. """
  683. Infers dynamic_shapes based on additional inputs.
  684. This is useful particularly for deployment engineers who, on the one hand, may
  685. have access to ample testing or profiling data that can provide a fair sense of
  686. representative inputs for a model, but on the other hand, may not know enough
  687. about the model to guess which input shapes should be dynamic.
  688. Input shapes that are different than the original are considered dynamic; conversely,
  689. those that are the same as the original are considered static. Moreover, we verify
  690. that the additional inputs are valid for the exported program. This guarantees that
  691. tracing with them instead of the original would have generated the same graph.
  692. Example::
  693. args0, kwargs0 = ... # example inputs for export
  694. # other representative inputs that the exported program will run on
  695. dynamic_shapes = torch.export.AdditionalInputs()
  696. dynamic_shapes.add(args1, kwargs1)
  697. ...
  698. dynamic_shapes.add(argsN, kwargsN)
  699. torch.export(..., args0, kwargs0, dynamic_shapes=dynamic_shapes)
  700. """
  701. def __init__(self):
  702. self._examples = []
  703. def add(self, args, kwargs=None):
  704. """
  705. Additional input :func:`args` and :func:`kwargs`.
  706. """
  707. if type(args) is not tuple:
  708. raise AssertionError(f"Representative args {args} must be a tuple")
  709. if kwargs is not None and type(kwargs) is not dict:
  710. raise AssertionError(
  711. f"Representative kwargs {kwargs} must be None or a dict"
  712. )
  713. self._examples.append((args, kwargs))
  714. def dynamic_shapes(self, m, args, kwargs=None):
  715. """
  716. Infers a :func:`dynamic_shapes` pytree structure by merging shapes of the
  717. original input :func:`args` and :func:`kwargs` and of each additional input
  718. args and kwargs.
  719. """
  720. dynamic_shapes, *other_dynamic_shapes = [
  721. _tree_map_with_path(
  722. lambda path, t: tuple(t.shape) if isinstance(t, torch.Tensor) else t,
  723. _combine_args(m, args, kwargs),
  724. )
  725. for args, kwargs in [(args, kwargs), *self._examples]
  726. ]
  727. def _mark_dynamism(v, *other_vs):
  728. if not all(type(v) is type(other) for other in other_vs):
  729. raise ValueError(
  730. "The following inputs were found to have differing types, "
  731. f"so they cannot be marked as dynamic: {(v,) + other_vs}."
  732. )
  733. if isinstance(v, int) and not isinstance(v, bool):
  734. if all(other_v == v for other_v in other_vs):
  735. return None
  736. else:
  737. return Dim.DYNAMIC
  738. else:
  739. if not all(other_v == v for other_v in other_vs):
  740. raise ValueError(
  741. "The following inputs were found to have differing values, "
  742. f"but they cannot be marked as dynamic: {(v,) + other_vs}."
  743. )
  744. return None
  745. return tree_map(
  746. _mark_dynamism,
  747. dynamic_shapes,
  748. *other_dynamic_shapes,
  749. is_leaf=lambda i: type(i) is int,
  750. )
  751. def verify(self, ep):
  752. """
  753. Verifies that an exported program is valid for each additional input.
  754. """
  755. epm = ep.module()
  756. for args, kwargs in self._examples:
  757. torch.export._unlift._check_input_constraints_for_module(
  758. epm, args, kwargs or {}
  759. )
  760. def _warn_on_None_dynamic_shape_dimension():
  761. msg = (
  762. "Using None as a dynamic shape dimension is deprecated. "
  763. "Please use Dim.STATIC instead"
  764. )
  765. # TODO(avik): raise an error in the future
  766. log.warning(msg)
  767. def _check_dynamic_shapes(
  768. combined_args: dict[str, Any],
  769. dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
  770. ):
  771. """
  772. Checks the dynamic_shapes specification for correctness,
  773. using combined args + kwargs as reference for inputs structure.
  774. """
  775. from torch._dynamo.exc import UserError, UserErrorType
  776. if dynamic_shapes is None or len(dynamic_shapes) == 0:
  777. return
  778. if isinstance(dynamic_shapes, (tuple, list)):
  779. combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc]
  780. bounds: dict[str, tuple[int, int]] = {}
  781. def check_same_bounds(dim):
  782. if dim.__name__ in bounds:
  783. min_, max_ = bounds[dim.__name__]
  784. if dim.min != min_ or dim.max != max_:
  785. this_ = Dim._readable(dim.__name__, min_, max_)
  786. that_ = Dim._readable(dim.__name__, dim.min, dim.max)
  787. raise UserError(
  788. UserErrorType.INVALID_INPUT,
  789. f"Found different definitions {this_} and {that_} "
  790. f"for the same symbolic dimension {dim}!",
  791. )
  792. else:
  793. bounds[dim.__name__] = (dim.min, dim.max)
  794. def check_symbols(path, tensor, shape):
  795. if isinstance(shape, dict):
  796. for i, dim in shape.items():
  797. if isinstance(dim, Dim):
  798. check_same_bounds(dim)
  799. elif dim is None:
  800. _warn_on_None_dynamic_shape_dimension()
  801. elif not (isinstance(dim, (int, _DimHint))):
  802. raise UserError(
  803. UserErrorType.INVALID_INPUT,
  804. f"Unexpected dimension mapped to index {i} in input tensor shape {shape} "
  805. f"specified at `dynamic_shapes{keystr(path)}` "
  806. f"(expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC, "
  807. f" but got {dim!r} instead)",
  808. case_name="dynamic_shapes_validation",
  809. )
  810. elif isinstance(shape, (tuple, list)):
  811. if len(shape) != len(tensor.shape):
  812. raise UserError(
  813. UserErrorType.INVALID_INPUT,
  814. f"Expected dynamic shape spec {shape} specified at `dynamic_shapes{keystr(path)}` "
  815. f"to have the same length as the actual tensor shape {tensor.shape} "
  816. f"(expected {len(tensor.shape)}, but got {len(shape)} instead)",
  817. case_name="dynamic_shapes_validation",
  818. )
  819. for i, dim in enumerate(shape):
  820. if isinstance(dim, Dim):
  821. check_same_bounds(dim)
  822. elif dim is None:
  823. _warn_on_None_dynamic_shape_dimension()
  824. elif not (isinstance(dim, (int, _DimHint))):
  825. raise UserError(
  826. UserErrorType.INVALID_INPUT,
  827. f"Unexpected dimension #{i} in input tensor shape {shape} "
  828. f"specified at `dynamic_shapes{keystr(path)}` "
  829. f"(expected None, an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC, "
  830. f"but got {dim!r} instead)",
  831. case_name="dynamic_shapes_validation",
  832. )
  833. elif shape is not None:
  834. raise UserError(
  835. UserErrorType.INVALID_INPUT,
  836. f"Unexpected input tensor shape {shape} specified at `dynamic_shapes{keystr(path)}` "
  837. f"(expected either a list/tuple of dimensions, or a dict mapping indices to dimensions,"
  838. f" where each dimension is an int, a Dim, Dim.AUTO, Dim.STATIC, or Dim.DYNAMIC)",
  839. case_name="dynamic_shapes_validation",
  840. )
  841. if not isinstance(dynamic_shapes, (dict, tuple, list)):
  842. raise AssertionError(
  843. f"expected dynamic_shapes to be dict, tuple, or list, got {type(dynamic_shapes)}"
  844. )
  845. if isinstance(dynamic_shapes, dict):
  846. got_keys = list(dynamic_shapes.keys())
  847. expected_arg_names = list(combined_args.keys())
  848. if sorted(got_keys) != sorted(expected_arg_names):
  849. msg = (
  850. f"When `dynamic_shapes` is specified as a dict, its top-level keys "
  851. f"must be the arg names {expected_arg_names} of `inputs`, but "
  852. f"here they are {got_keys}. "
  853. )
  854. if (
  855. len(combined_args) == 1
  856. and expected_arg_names[0] not in got_keys
  857. and isinstance(combined_args[expected_arg_names[0]], dict)
  858. ):
  859. msg += (
  860. "Since here `inputs` is a list/tuple enclosing a single dict, "
  861. "maybe you just forgot to enclose `dynamic_shapes` in a list/tuple?"
  862. )
  863. else:
  864. msg += (
  865. "Alternatively, you could also ignore arg names entirely "
  866. "and specify `dynamic_shapes` as a list/tuple matching `inputs`."
  867. )
  868. raise UserError(
  869. UserErrorType.INVALID_INPUT, msg, case_name="dynamic_shapes_validation"
  870. )
  871. def check_shape(path, t, dynamic_shape):
  872. if isinstance(t, torch.Tensor):
  873. check_symbols(path, t, dynamic_shape)
  874. elif isinstance(t, _IntWrapper):
  875. if isinstance(dynamic_shape, _Dim):
  876. raise ValueError(
  877. "Unable to specify input integers as dynamic through named "
  878. "Dims. Please use Dim.AUTO/DYNAMIC instead."
  879. )
  880. if dynamic_shape is not None and not isinstance(
  881. dynamic_shape, (int, _DimHint)
  882. ):
  883. raise AssertionError(
  884. f"expected dynamic_shape to be None, int, or _DimHint for _IntWrapper, got {type(dynamic_shape)}"
  885. )
  886. else:
  887. if dynamic_shape is not None:
  888. rendered_path = keystr(path)
  889. raise UserError(
  890. UserErrorType.INVALID_INPUT,
  891. f"Cannot associate shape {dynamic_shape} specified at `dynamic_shapes{rendered_path}` "
  892. f"to non-tensor type {type(t)} at `inputs{rendered_path}` (expected None)",
  893. case_name="dynamic_shapes_validation",
  894. )
  895. _tree_map_with_path(check_shape, combined_args, dynamic_shapes, tree_name="inputs")
  896. def _process_dynamic_shapes(
  897. combined_args: dict[str, Any],
  898. dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
  899. ) -> list[Constraint]:
  900. """
  901. Reads the dynamic_shapes specification and produces a list of constraints.
  902. """
  903. from torch._dynamo.exc import UserError, UserErrorType
  904. if dynamic_shapes is None or len(dynamic_shapes) == 0:
  905. # we run with dynamic by default, so no need to produce constraints
  906. return []
  907. if isinstance(dynamic_shapes, (tuple, list)):
  908. combined_args = type(dynamic_shapes)(combined_args.values()) # type: ignore[assignment, misc]
  909. # map of Dim names representing input shape dimensions to constraints on them
  910. symbols: dict[str, list[Constraint]] = defaultdict(list)
  911. # track roots that do not directly represent input shape dimensions
  912. phantom_roots: dict[str, _PhantomRoot] = {}
  913. derived_constraints_with_phantom_root: list[_DerivedConstraint] = []
  914. # list of constraints to return
  915. constraints: list[Constraint] = []
  916. def to_constraint(dim, tensor, i):
  917. import sympy
  918. from torch.fx.experimental.symbolic_shapes import StrictMinMaxConstraint
  919. from torch.utils._sympy.solve import try_solve
  920. from torch.utils._sympy.value_ranges import ValueRanges
  921. def root_value():
  922. # given tensor.shape[i] is the value of dim = fn(root),
  923. # find the value of root
  924. symbol = sympy.Symbol(dim.root.__name__, integer=True)
  925. expr = dim.fn(symbol)
  926. solution = try_solve(sympy.Eq(expr, tensor.shape[i]), symbol)
  927. if solution is not None:
  928. return int(solution[1])
  929. else:
  930. raise UserError( # noqa: B904
  931. UserErrorType.CONSTRAINT_VIOLATION,
  932. f"Expected shape[{i}] = {tensor.shape[i]} of input Tensor to be "
  933. f"of the form {expr}, where {symbol} is an integer",
  934. )
  935. if isinstance(dim, _DerivedDim):
  936. # generate a _DerivedConstraint where the root is:
  937. # - either a _ConstraintTarget (if dim.root directly describes an input shape)
  938. # - or a _PhantomRoot (otherwise)
  939. dim_root = dim.root # type: ignore[attr-defined]
  940. if dim_root.__name__ in symbols:
  941. # root represents an input shape dimension
  942. root_constraint = symbols[dim_root.__name__][0]
  943. root = _ConstraintTarget(
  944. root_constraint.t_id,
  945. root_constraint.dim,
  946. )
  947. elif dim_root.__name__ not in phantom_roots:
  948. # create a phantom root
  949. root = _PhantomRoot( # type: ignore[assignment]
  950. name=dim_root.__name__,
  951. constraint_range=StrictMinMaxConstraint(
  952. vr=ValueRanges(lower=dim_root.min, upper=dim_root.max),
  953. warn_only=False,
  954. ),
  955. val=root_value(),
  956. )
  957. phantom_roots[dim_root.__name__] = root # type: ignore[assignment]
  958. else:
  959. root = phantom_roots[dim_root.__name__] # type: ignore[assignment]
  960. constraint = _DerivedConstraint(
  961. id(tensor),
  962. i,
  963. dim.__name__,
  964. StrictMinMaxConstraint(
  965. vr=ValueRanges(lower=dim.min, upper=dim.max),
  966. warn_only=False,
  967. ),
  968. root,
  969. dim.fn, # type: ignore[attr-defined]
  970. )
  971. if isinstance(root, _PhantomRoot):
  972. # NOTE(avik): since we have not processed all inputs yet, we may replace this
  973. # with a root that does represent an input shape dimension later (see below)
  974. derived_constraints_with_phantom_root.append(constraint)
  975. elif isinstance(dim, _StaticDim):
  976. constraint = _Constraint( # type: ignore[assignment]
  977. id(tensor),
  978. i,
  979. dim.__name__,
  980. StrictMinMaxConstraint(
  981. vr=ValueRanges(lower=dim.value, upper=dim.value), # type: ignore[attr-defined]
  982. warn_only=False,
  983. ),
  984. )
  985. else:
  986. if not isinstance(dim, Dim):
  987. raise AssertionError(f"expected dim to be Dim, got {type(dim)}")
  988. constraint = _Constraint( # type: ignore[assignment]
  989. id(tensor),
  990. i,
  991. dim.__name__,
  992. StrictMinMaxConstraint(
  993. vr=ValueRanges(lower=dim.min, upper=dim.max), # type: ignore[attr-defined]
  994. warn_only=False,
  995. ),
  996. )
  997. return constraint
  998. def _parse_tensor_dim(tensor, idx, dim) -> None:
  999. def _create_static_dim(tensor, i, value):
  1000. return _StaticDim(value)
  1001. if isinstance(dim, (int, Dim)):
  1002. if isinstance(dim, int):
  1003. dim = _create_static_dim(tensor, idx, dim)
  1004. constraint = to_constraint(dim, tensor, idx)
  1005. symbols[dim.__name__].append(constraint)
  1006. elif isinstance(dim, _DimHint):
  1007. if dim.type == _DimHintType.AUTO:
  1008. torch._dynamo.maybe_mark_dynamic(tensor, idx)
  1009. elif dim.type == _DimHintType.STATIC:
  1010. torch._dynamo.mark_static(tensor, idx)
  1011. elif dim.type == _DimHintType.DYNAMIC:
  1012. torch._dynamo.mark_dynamic(tensor, idx)
  1013. constraints.append(_RelaxedConstraint(id(tensor), idx))
  1014. elif dim is None:
  1015. torch._dynamo.mark_static(tensor, idx)
  1016. def update_symbols(path, tensor, shape):
  1017. # clean out decorators from user side, or previous export call
  1018. # we also delete these attributes in non_strict_utils.py/make_constraints()
  1019. tensor._dynamo_weak_dynamic_indices = set()
  1020. tensor._dynamo_dynamic_indices = set()
  1021. tensor._dynamo_dynamic_range = set()
  1022. tensor._dynamo_static_indices = set()
  1023. tensor._dynamo_unbacked_indices = set()
  1024. if isinstance(shape, dict):
  1025. for i, dim in shape.items():
  1026. _parse_tensor_dim(tensor, i, dim)
  1027. elif isinstance(shape, (tuple, list)):
  1028. for i, dim in enumerate(shape):
  1029. _parse_tensor_dim(tensor, i, dim)
  1030. elif shape is None:
  1031. for i in range(tensor.dim()):
  1032. _parse_tensor_dim(tensor, i, None)
  1033. def assoc_shape(path, t, dynamic_shape):
  1034. if isinstance(t, torch.Tensor):
  1035. update_symbols(path, t, dynamic_shape)
  1036. elif isinstance(t, _IntWrapper):
  1037. # If tensor dimensions are marked as dynamic, the tensors themselves
  1038. # get marked using mark_dynamic. However since we can't mark
  1039. # integers as dynamic, we first wrap integers in this class, and
  1040. # then set the `dim` field of the class with the dynamic shapes dim
  1041. # to mark the integer as dynamic.
  1042. t.dynamism = dynamic_shape
  1043. _tree_map_with_path(assoc_shape, combined_args, dynamic_shapes, tree_name="inputs")
  1044. for derived_constraint_with_phantom_root in derived_constraints_with_phantom_root:
  1045. phantom_root_name = derived_constraint_with_phantom_root.root.name # type: ignore[union-attr]
  1046. if phantom_root_name in symbols:
  1047. # We found an input shape dimension corresponding to this name, so we
  1048. # do not need a phantom symbol for it after all.
  1049. # NOTE(avik): Overall we want to maintain the invariant that roots that
  1050. # are phantom symbols are really "phantom," i.e., they cannot be represented
  1051. # by any input source. This is important when we are deciding derived equalities,
  1052. # since we can focus our attention exclusively on input sources: deciding
  1053. # derived equalities involving phantom symbols are, in comparison, trivial.
  1054. derived_constraint_with_phantom_root.root = symbols[phantom_root_name][0]
  1055. for dynamic_dims in symbols.values():
  1056. constraints.extend(dynamic_dims)
  1057. return constraints
  1058. def _get_dim_name_mapping(
  1059. dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any] | None,
  1060. ):
  1061. name_to_dim = {}
  1062. for dim in tree_iter(dynamic_shapes, is_leaf=lambda x: isinstance(x, Dim)):
  1063. if dim is None:
  1064. # NOTE: this must denote a non-Tensor or automatic at this point.
  1065. continue
  1066. if isinstance(dim, int):
  1067. continue
  1068. elif isinstance(dim, Dim):
  1069. name_to_dim[dim.__name__] = dim
  1070. if isinstance(dim, _DerivedDim):
  1071. name_to_dim[dim.root.__name__] = dim.root # type: ignore[attr-defined]
  1072. else:
  1073. if not isinstance(dim, _DimHint):
  1074. raise AssertionError(f"expected dim to be _DimHint, got {type(dim)}")
  1075. return name_to_dim
  1076. def refine_dynamic_shapes_from_suggested_fixes(
  1077. msg: str,
  1078. dynamic_shapes: dict[str, Any] | tuple[Any] | list[Any],
  1079. ) -> dict[str, Any] | tuple[Any] | list[Any]:
  1080. """
  1081. When exporting with :func:`dynamic_shapes`, export may fail with a ConstraintViolation error if the specification
  1082. doesn't match the constraints inferred from tracing the model. The error message may provide suggested fixes -
  1083. changes that can be made to :func:`dynamic_shapes` to export successfully.
  1084. Example ConstraintViolation error message::
  1085. Suggested fixes:
  1086. dim = Dim('dim', min=3, max=6) # this just refines the dim's range
  1087. dim = 4 # this specializes to a constant
  1088. dy = dx + 1 # dy was specified as an independent dim, but is actually tied to dx with this relation
  1089. This is a helper function that takes the ConstraintViolation error message and the original :func:`dynamic_shapes` spec,
  1090. and returns a new :func:`dynamic_shapes` spec that incorporates the suggested fixes.
  1091. Example usage::
  1092. try:
  1093. ep = export(mod, args, dynamic_shapes=dynamic_shapes)
  1094. except torch._dynamo.exc.UserError as exc:
  1095. new_shapes = refine_dynamic_shapes_from_suggested_fixes(
  1096. exc.msg, dynamic_shapes
  1097. )
  1098. ep = export(mod, args, dynamic_shapes=new_shapes)
  1099. """
  1100. import re
  1101. import sympy
  1102. from torch._dynamo.exc import UserError, UserErrorType
  1103. from torch.fx.experimental.symbolic_shapes import _is_supported_equivalence
  1104. try:
  1105. shape_fixes_msg = msg.split("Suggested fixes:")[1].strip()
  1106. except Exception as exc:
  1107. raise UserError(
  1108. UserErrorType.INVALID_INPUT,
  1109. "Suggested fixes not found in error message given to refine_dynamic_shapes_from_suggested_fixes()",
  1110. ) from exc
  1111. # build shape_fixes dictionary
  1112. shape_fixes = {}
  1113. for fix in shape_fixes_msg.split("\n"):
  1114. fix = fix.strip()
  1115. if match := re.match(r"(.*) = Dim\('(.*)'.*\)", fix):
  1116. name = match.group(1)
  1117. _min, _max = None, None
  1118. if match_min := re.match(r".* = Dim\('.*', min\=([0-9]+).*\)", fix):
  1119. _min = int(match_min.group(1))
  1120. if match_max := re.match(r".* = Dim\('.*'.*max\=([0-9]+)\)", fix):
  1121. _max = int(match_max.group(1))
  1122. shape_fixes[name] = Dim(name, min=_min, max=_max)
  1123. else:
  1124. name, expr = fix.split(" = ")
  1125. expr = sympy.sympify(expr)
  1126. if isinstance(expr, sympy.Number):
  1127. # static, integer
  1128. shape_fixes[name] = int(expr) # type: ignore[assignment]
  1129. else:
  1130. # relation or derived dim
  1131. shape_fixes[name] = expr
  1132. name_to_dim = _get_dim_name_mapping(dynamic_shapes)
  1133. # track derived dim roots
  1134. roots: set[str] = set()
  1135. for k, c in shape_fixes.items():
  1136. if not isinstance(c, (int, Dim, _DerivedDim, sympy.Expr)):
  1137. raise AssertionError(
  1138. f"expected shape_fixes[{k!r}] to be int, Dim, _DerivedDim, or sympy.Expr, got {type(c)}"
  1139. )
  1140. if isinstance(c, sympy.Expr): # check dim/derived dim expression
  1141. if not _is_supported_equivalence(c):
  1142. raise AssertionError(f"sympy.Expr {c} is not a supported equivalence")
  1143. shape_fixes[k] = c
  1144. roots.add(str(next(iter(c.free_symbols))))
  1145. if isinstance(c, _DerivedDim):
  1146. roots.add(c.root.__name__) # type: ignore[attr-defined]
  1147. # check keys are existing dims or new roots
  1148. for k in shape_fixes:
  1149. if k not in name_to_dim and k not in roots:
  1150. raise AssertionError(
  1151. f"shape_fixes key {k!r} not found in name_to_dim or roots"
  1152. )
  1153. # cache so we don't produce multiple derived dim objects
  1154. derived_dim_cache: dict[str, _DerivedDim] = {}
  1155. def apply_fixes(path, dim, dummy):
  1156. if dim is None or isinstance(dim, int): # not dynamic
  1157. return dim
  1158. elif dim.__name__ in shape_fixes: # directly fix
  1159. fix = shape_fixes[dim.__name__]
  1160. if isinstance(fix, sympy.Expr): # now derived or related
  1161. if str(fix) in derived_dim_cache:
  1162. return derived_dim_cache[str(fix)]
  1163. else:
  1164. symbol = next(iter(fix.free_symbols))
  1165. # try to locate symbol
  1166. if symbol.name in shape_fixes:
  1167. root = shape_fixes[symbol.name]
  1168. else:
  1169. if symbol.name not in name_to_dim:
  1170. raise AssertionError(
  1171. f"symbol.name {symbol.name!r} not found in name_to_dim"
  1172. )
  1173. root = name_to_dim[symbol.name]
  1174. # figure out value of fix
  1175. modulus, remainder = sympy.polys.polytools.div(fix, symbol)
  1176. dim = root
  1177. if modulus != 1:
  1178. dim = int(modulus) * dim
  1179. if remainder != 0:
  1180. dim = dim + int(remainder)
  1181. # pyrefly: ignore [unsupported-operation]
  1182. derived_dim_cache[str(fix)] = dim
  1183. return dim
  1184. else:
  1185. return fix
  1186. elif isinstance(dim, _DerivedDim) and dim.root.__name__ in shape_fixes: # type: ignore[attr-defined]
  1187. if dim.__name__ in derived_dim_cache:
  1188. return derived_dim_cache[dim.__name__]
  1189. else: # evaluate new derived value based on root
  1190. _dim = dim.fn(shape_fixes[dim.root.__name__]) # type: ignore[attr-defined]
  1191. derived_dim_cache[dim.__name__] = _dim
  1192. return _dim
  1193. return dim # unchanged dim
  1194. return _tree_map_with_path(apply_fixes, dynamic_shapes, dynamic_shapes)