builtin.py 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881
  1. # mypy: allow-untyped-defs
  2. """
  3. Built-in function and type variable tracking for TorchDynamo's symbolic execution.
  4. This module contains variable tracker classes for Python built-in functions, types,
  5. and operations during graph compilation. It handles symbolic execution of:
  6. - Built-in functions (len, getattr, isinstance, etc.)
  7. - Type constructors (int, float, str, list, dict, etc.)
  8. - Built-in operators and methods
  9. - Special Python constructs (super, hasattr, etc.)
  10. Key classes:
  11. - BuiltinVariable: Tracks built-in functions and handles their execution
  12. - TypeVariable: Manages type constructor calls and type checking
  13. - SuperVariable: Handles super() calls in class hierarchies
  14. These variable trackers ensure that built-in Python operations are correctly
  15. handled during symbolic execution, either by executing them directly when safe
  16. or by creating appropriate graph nodes when needed.
  17. """
  18. import contextlib
  19. import functools
  20. import inspect
  21. import itertools
  22. import logging
  23. import math
  24. import operator
  25. import sys
  26. import types
  27. import typing
  28. import unittest
  29. from collections import defaultdict, OrderedDict
  30. from collections.abc import Iterable, KeysView, Sequence
  31. from typing import Any, Callable, TYPE_CHECKING, Union
  32. import torch
  33. from torch import sym_float, sym_int
  34. from torch._subclasses.meta_utils import is_sparse_any
  35. from torch.overrides import BaseTorchFunctionMode
  36. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  37. from .. import config, graph_break_hints, polyfills, variables
  38. from ..exc import (
  39. AttributeMutationError,
  40. ObservedAttributeError,
  41. ObservedUserStopIteration,
  42. raise_observed_exception,
  43. unimplemented_v2,
  44. Unsupported,
  45. UserError,
  46. UserErrorType,
  47. )
  48. from ..guards import GuardBuilder, install_guard
  49. from ..replay_record import DummyModule
  50. from ..source import (
  51. AttrSource,
  52. GetItemSource,
  53. GlobalSource,
  54. is_constant_source,
  55. TypeSource,
  56. )
  57. from ..utils import (
  58. check_constant_args,
  59. check_numpy_ndarray_args,
  60. check_unspec_or_constant_args,
  61. check_unspec_python_args,
  62. cmp_name_to_op_mapping,
  63. dict_methods,
  64. extract_fake_example_value,
  65. frozenset_methods,
  66. get_fake_value,
  67. guard_if_dyn,
  68. is_tensor_getset_descriptor,
  69. is_wrapper_or_member_descriptor,
  70. istype,
  71. numpy_operator_wrapper,
  72. proxy_args_kwargs,
  73. set_methods,
  74. str_methods,
  75. tensortype_to_dtype,
  76. )
  77. from .base import AsPythonConstantNotImplementedError, ValueMutationNew, VariableTracker
  78. from .constant import ConstantVariable
  79. from .ctx_manager import EventVariable, StreamVariable
  80. from .dicts import (
  81. ConstDictVariable,
  82. DefaultDictVariable,
  83. DictKeysVariable,
  84. DictViewVariable,
  85. FrozensetVariable,
  86. is_hashable,
  87. SetVariable,
  88. )
  89. from .lists import (
  90. BaseListVariable,
  91. ListIteratorVariable,
  92. ListVariable,
  93. SizeVariable,
  94. TupleIteratorVariable,
  95. TupleVariable,
  96. )
  97. from .tensor import (
  98. FakeItemVariable,
  99. supported_comparison_ops,
  100. SymNodeVariable,
  101. TensorVariable,
  102. UnspecializedPythonVariable,
  103. )
  104. from .user_defined import (
  105. MutableMappingVariable,
  106. UserDefinedDictVariable,
  107. UserDefinedObjectVariable,
  108. UserDefinedVariable,
  109. )
  110. if TYPE_CHECKING:
  111. # Cyclic dependency...
  112. from torch._dynamo.codegen import PyCodegen
  113. from torch._dynamo.symbolic_convert import InstructionTranslator
  114. log = logging.getLogger(__name__)
  115. IN_PLACE_DESUGARING_MAP = {
  116. operator.iadd: operator.add,
  117. operator.isub: operator.sub,
  118. operator.imul: operator.mul,
  119. operator.ifloordiv: operator.floordiv,
  120. operator.itruediv: operator.truediv,
  121. operator.imod: operator.mod,
  122. operator.imatmul: operator.imatmul,
  123. operator.ilshift: operator.lshift,
  124. operator.irshift: operator.rshift,
  125. operator.ipow: operator.pow,
  126. operator.iand: operator.and_,
  127. operator.ior: operator.or_,
  128. operator.ixor: operator.xor,
  129. }
  130. _HandlerCallback = Callable[
  131. ["InstructionTranslator", typing.Any, typing.Any], VariableTracker
  132. ]
  133. _TrackersType = Union[type[VariableTracker], tuple[type[VariableTracker], ...]]
  134. polyfill_fn_mapping = {
  135. operator.eq: polyfills.cmp_eq,
  136. operator.ne: polyfills.cmp_ne,
  137. operator.lt: polyfills.cmp_lt,
  138. operator.le: polyfills.cmp_le,
  139. operator.gt: polyfills.cmp_gt,
  140. operator.ge: polyfills.cmp_ge,
  141. }
  142. bin_ops = (
  143. operator.pow,
  144. operator.mul,
  145. operator.matmul,
  146. operator.floordiv,
  147. operator.truediv,
  148. operator.mod,
  149. operator.add,
  150. operator.lt,
  151. operator.gt,
  152. operator.ge,
  153. operator.le,
  154. operator.ne,
  155. operator.eq,
  156. operator.sub,
  157. operator.ipow,
  158. operator.imul,
  159. operator.imatmul,
  160. operator.ifloordiv,
  161. operator.itruediv,
  162. operator.imod,
  163. operator.iadd,
  164. operator.isub,
  165. )
  166. bin_int_ops = (
  167. operator.and_,
  168. operator.or_,
  169. operator.xor,
  170. operator.iand,
  171. operator.ixor,
  172. operator.ior,
  173. )
  174. un_int_ops = (operator.invert,)
  175. tensor_and_int_ops = (
  176. operator.lshift,
  177. operator.rshift,
  178. operator.ilshift,
  179. operator.irshift,
  180. operator.getitem,
  181. )
  182. un_ops = (
  183. operator.abs,
  184. operator.pos,
  185. operator.neg,
  186. operator.not_, # Note: this has a local scalar dense call
  187. operator.length_hint,
  188. )
  189. BUILTIN_TO_TENSOR_FN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {}
  190. # These functions represent the r* versions of the above ops
  191. # Basically, if __add__(1, Tensor) is called, it is translated
  192. # to __radd__(Tensor, 1).
  193. # In the builtin var, we check if there is a tensor in the first args position,
  194. # if not, we swap the args and use the r* version of the op.
  195. BUILTIN_TO_TENSOR_RFN_MAP: dict[Callable[..., Any], Callable[..., Any]] = {}
  196. def populate_builtin_to_tensor_fn_map():
  197. global BUILTIN_TO_TENSOR_FN_MAP
  198. if len(BUILTIN_TO_TENSOR_FN_MAP) > 0:
  199. # Only populate once; after there are elements present no need to
  200. # repopulate
  201. return
  202. most_recent_func = None
  203. class GetMethodMode(BaseTorchFunctionMode):
  204. """
  205. Mode to extract the correct methods from torch function invocations
  206. (Used to get the correct torch.Tensor methods from builtins)
  207. """
  208. def __torch_function__(self, func, types, args=(), kwargs=None):
  209. kwargs = kwargs or {}
  210. nonlocal most_recent_func
  211. most_recent_func = func
  212. return func(*args, **kwargs)
  213. inp0 = torch.ones(1)
  214. inp1 = torch.ones(1)
  215. inp0_int = torch.ones(1, dtype=torch.int32)
  216. inp1_int = torch.ones(1, dtype=torch.int32)
  217. with GetMethodMode():
  218. setups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [
  219. (lambda o: o(inp0), un_ops),
  220. (lambda o: o(inp0_int), un_int_ops),
  221. (lambda o: o(inp0, inp1), bin_ops),
  222. (lambda o: o(inp0_int, inp1_int), bin_int_ops),
  223. (lambda o: o(inp0_int, 0), tensor_and_int_ops),
  224. ]
  225. for setup_fn, op_list in setups_and_oplists:
  226. for op in op_list:
  227. setup_fn(op)
  228. assert most_recent_func is not None
  229. BUILTIN_TO_TENSOR_FN_MAP[op] = most_recent_func
  230. # gather the reverse functions
  231. rsetups_and_oplists: list[tuple[Callable[..., Any], Iterable[Any]]] = [
  232. (
  233. lambda o: o(1, inp1),
  234. bin_ops,
  235. ), # Get r* ops, (ex. __sub__(int, Tensor) -> __rsub__(Tensor, int))
  236. (lambda o: o(1, inp1_int), bin_int_ops),
  237. (lambda o: o(0, inp0_int), tensor_and_int_ops),
  238. ]
  239. rskips = {operator.matmul, operator.imatmul, operator.getitem}
  240. for setup_fn, op_list in rsetups_and_oplists:
  241. for op in op_list:
  242. if op in rskips:
  243. continue
  244. setup_fn(op)
  245. assert most_recent_func is not None
  246. if most_recent_func != BUILTIN_TO_TENSOR_FN_MAP[op]:
  247. BUILTIN_TO_TENSOR_RFN_MAP[op] = most_recent_func
  248. class BuiltinVariable(VariableTracker):
  249. """
  250. A VariableTracker that represents a built-in value (functions and operators).
  251. A lot of the code here assumes it will be a function object.
  252. The BuiltinVariable class wraps Python built-in functions (like len, isinstance, etc.)
  253. and operators (like +, -, *, etc.) to enable symbolic execution during tracing. This allows
  254. Dynamo to properly handle these operations when converting Python code to FX graphs while
  255. maintaining correct semantics and enabling optimizations.
  256. """
  257. _SENTINEL = object()
  258. _nonvar_fields = {
  259. "fn",
  260. *VariableTracker._nonvar_fields,
  261. }
  262. @classmethod
  263. def create_with_source(cls, value, source):
  264. install_guard(source.make_guard(GuardBuilder.BUILTIN_MATCH))
  265. return cls(value, source=source)
  266. @staticmethod
  267. @functools.cache
  268. def _constant_fold_functions():
  269. fns = {
  270. abs,
  271. all,
  272. any,
  273. bool,
  274. callable,
  275. chr,
  276. complex,
  277. divmod,
  278. float,
  279. getattr,
  280. int,
  281. len,
  282. max,
  283. min,
  284. ord,
  285. pow,
  286. repr,
  287. round,
  288. str,
  289. str.format,
  290. sum,
  291. type,
  292. operator.abs,
  293. operator.pos,
  294. operator.neg,
  295. operator.not_,
  296. operator.truth,
  297. operator.invert,
  298. operator.pow,
  299. operator.mul,
  300. operator.matmul,
  301. operator.floordiv,
  302. operator.truediv,
  303. operator.mod,
  304. operator.add,
  305. operator.sub,
  306. operator.getitem,
  307. operator.length_hint,
  308. operator.lshift,
  309. operator.rshift,
  310. operator.and_,
  311. operator.or_,
  312. operator.xor,
  313. operator.ipow,
  314. operator.imul,
  315. operator.imatmul,
  316. operator.ifloordiv,
  317. operator.itruediv,
  318. operator.imod,
  319. operator.iadd,
  320. operator.isub,
  321. operator.ilshift,
  322. operator.irshift,
  323. operator.iand,
  324. operator.ixor,
  325. operator.ior,
  326. operator.index,
  327. }
  328. from .tensor import supported_comparison_ops
  329. fns.update(supported_comparison_ops.values())
  330. fns.update(x for x in math.__dict__.values() if isinstance(x, type(math.sqrt)))
  331. return fns
  332. def can_constant_fold_through(self):
  333. return self.fn in self._constant_fold_functions()
  334. @staticmethod
  335. @functools.cache
  336. def _fx_graph_functions():
  337. fns = {
  338. operator.abs,
  339. operator.pos,
  340. operator.neg,
  341. operator.not_,
  342. operator.invert,
  343. operator.pow,
  344. operator.mul,
  345. operator.matmul,
  346. operator.floordiv,
  347. operator.truediv,
  348. operator.mod,
  349. operator.add,
  350. operator.lt,
  351. operator.gt,
  352. operator.ge,
  353. operator.le,
  354. operator.ne,
  355. operator.eq,
  356. operator.sub,
  357. operator.length_hint,
  358. operator.lshift,
  359. operator.rshift,
  360. operator.and_,
  361. operator.or_,
  362. operator.xor,
  363. operator.ipow,
  364. operator.imul,
  365. operator.imatmul,
  366. operator.ifloordiv,
  367. operator.itruediv,
  368. operator.getitem,
  369. operator.imod,
  370. operator.iadd,
  371. operator.isub,
  372. operator.ilshift,
  373. operator.irshift,
  374. operator.iand,
  375. operator.ixor,
  376. operator.ior,
  377. }
  378. return fns
  379. @staticmethod
  380. @functools.cache
  381. def _binops() -> dict[
  382. Callable[..., object], tuple[list[str], Callable[..., object]]
  383. ]:
  384. # function -> ([forward name, reverse name, in-place name], in-place op)
  385. fns: dict[Callable[..., object], tuple[list[str], Callable[..., object]]] = {
  386. operator.add: (["__add__", "__radd__", "__iadd__"], operator.iadd),
  387. operator.sub: (["__sub__", "__rsub__", "__isub__"], operator.isub),
  388. operator.mul: (["__mul__", "__rmul__", "__imul__"], operator.imul),
  389. operator.truediv: (
  390. ["__truediv__", "__rtruediv__", "__itruediv__"],
  391. operator.itruediv,
  392. ),
  393. operator.floordiv: (
  394. ["__floordiv__", "__rfloordiv__", "__ifloordiv__"],
  395. operator.ifloordiv,
  396. ),
  397. operator.mod: (["__mod__", "__rmod__", "__imod__"], operator.imod),
  398. pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow),
  399. operator.pow: (["__pow__", "__rpow__", "__ipow__"], operator.ipow),
  400. operator.lshift: (
  401. ["__lshift__", "__rlshift__", "__ilshift__"],
  402. operator.ilshift,
  403. ),
  404. operator.rshift: (
  405. ["__rshift__", "__rrshift__", "__irshift__"],
  406. operator.irshift,
  407. ),
  408. # NB: The follow binary operators are not supported for now, since the
  409. # corresponding magic methods aren't defined on SymInt / SymFloat:
  410. # operator.matmul
  411. # divmod
  412. # operator.and_
  413. # operator.or_
  414. # operator.xor
  415. }
  416. return fns
  417. @staticmethod
  418. @functools.cache
  419. def _binop_handlers():
  420. # Multiple dispatch mechanism defining custom binop behavior for certain type
  421. # combinations. Handlers are attempted in order, and will be used if the type checks
  422. # match. They are expected to have the signature:
  423. # fn(tx, arg0: VariableTracker, arg1: VariableTracker) -> VariableTracker
  424. from .functions import BaseUserFunctionVariable, UserFunctionVariable
  425. from .nn_module import NNModuleVariable
  426. from .tensor import supported_const_comparison_ops
  427. from .torch import BaseTorchVariable
  428. from .user_defined import (
  429. UserDefinedClassVariable,
  430. UserDefinedObjectVariable,
  431. UserDefinedVariable,
  432. )
  433. # Override table contains: op_fn -> [list of handlers]
  434. op_handlers: dict[
  435. Callable[..., object],
  436. list[
  437. tuple[
  438. tuple[
  439. type[VariableTracker],
  440. _TrackersType,
  441. ],
  442. _HandlerCallback,
  443. ]
  444. ],
  445. ] = {}
  446. for (
  447. op,
  448. (magic_method_names, in_place_op),
  449. ) in BuiltinVariable._binops().items():
  450. op_handlers[op] = []
  451. op_handlers[in_place_op] = []
  452. forward_name, reverse_name, inplace_name = magic_method_names
  453. # User-defined args (highest precedence)
  454. def user_defined_handler(
  455. tx,
  456. a,
  457. b,
  458. *,
  459. forward_name=forward_name,
  460. reverse_name=reverse_name,
  461. ):
  462. # Manually handle reversing logic if needed (e.g. call __radd__)
  463. # TODO: If we expand this to handle tensor args, we need to manually
  464. # handle cases like this:
  465. #
  466. # class A(int):
  467. # def __radd__(self, other):
  468. # print("woof")
  469. # torch.randn(3) + A(3)
  470. #
  471. # In this example, A.__radd__() is not called -> nothing is printed, because
  472. # Tensor.__add__ only does a subtype test against int, ignoring the subclass.
  473. # To be fully correct, we should not call A.__radd__() here, and there may be
  474. # other cases to reason about and add exceptions for.
  475. if isinstance(a, UserDefinedVariable):
  476. return a.call_method(tx, forward_name, [b], {})
  477. else:
  478. return b.call_method(tx, reverse_name, [a], {})
  479. op_handlers[op].append(
  480. ((UserDefinedVariable, VariableTracker), user_defined_handler)
  481. )
  482. op_handlers[op].append(
  483. ((VariableTracker, UserDefinedVariable), user_defined_handler)
  484. )
  485. def user_defined_inplace_handler(
  486. tx: "InstructionTranslator", a, b, *, forward_name=inplace_name
  487. ):
  488. return a.call_method(tx, forward_name, [b], {})
  489. op_handlers[in_place_op].append(
  490. ((UserDefinedVariable, VariableTracker), user_defined_inplace_handler)
  491. )
  492. op_handlers[in_place_op].append(
  493. ((VariableTracker, UserDefinedVariable), user_defined_inplace_handler)
  494. )
  495. # Dynamic shape args
  496. def dynamic_handler(tx: "InstructionTranslator", a, b, *, fn=op):
  497. from .builder import wrap_fx_proxy
  498. return wrap_fx_proxy(
  499. tx,
  500. tx.output.create_proxy(
  501. "call_function", fn, *proxy_args_kwargs([a, b], {})
  502. ),
  503. )
  504. op_handlers[op].append(
  505. ((SymNodeVariable, VariableTracker), dynamic_handler)
  506. )
  507. op_handlers[op].append(
  508. ((VariableTracker, SymNodeVariable), dynamic_handler)
  509. )
  510. # NB: Prefer out-of-place op when calling in-place op to generate valid graph
  511. op_handlers[in_place_op].append(
  512. ((SymNodeVariable, VariableTracker), dynamic_handler)
  513. )
  514. op_handlers[in_place_op].append(
  515. ((VariableTracker, SymNodeVariable), dynamic_handler)
  516. )
  517. # Special cases - lower precedence but still prefer these over constant folding
  518. # List-like addition (e.g. [1, 2] + [3, 4])
  519. def tuple_add_handler(tx: "InstructionTranslator", a, b):
  520. return TupleVariable([*a.items, *b.unpack_var_sequence(tx)])
  521. def size_add_handler(tx: "InstructionTranslator", a, b):
  522. return SizeVariable([*a.items, *b.unpack_var_sequence(tx)])
  523. list_like_addition_handlers: list[
  524. tuple[
  525. tuple[
  526. type[VariableTracker],
  527. _TrackersType,
  528. ],
  529. _HandlerCallback,
  530. ]
  531. ] = [
  532. # NB: Prefer the tuple-specific logic over base logic because of
  533. # some SizeVariable weirdness. Specifically, the tuple-specific logic
  534. # drops the subclass type (e.g. SizeVariable) and returns TupleVariables.
  535. (
  536. (SizeVariable, SizeVariable),
  537. size_add_handler,
  538. ),
  539. (
  540. (SizeVariable, TupleVariable),
  541. size_add_handler,
  542. ),
  543. (
  544. (TupleVariable, SizeVariable),
  545. size_add_handler,
  546. ),
  547. (
  548. (TupleVariable, TupleVariable),
  549. tuple_add_handler,
  550. ),
  551. (
  552. (TupleVariable, ConstantVariable),
  553. tuple_add_handler,
  554. ),
  555. (
  556. (ConstantVariable, TupleVariable),
  557. lambda tx, a, b: TupleVariable(
  558. [
  559. *a.unpack_var_sequence(tx),
  560. *b.items,
  561. ],
  562. ),
  563. ),
  564. (
  565. (
  566. ListVariable,
  567. (BaseListVariable, ConstantVariable, ListIteratorVariable),
  568. ),
  569. lambda tx, a, b: ListVariable(
  570. [*a.items, *b.unpack_var_sequence(tx)],
  571. mutation_type=ValueMutationNew(),
  572. ),
  573. ),
  574. (
  575. (BaseListVariable, BaseListVariable),
  576. lambda tx, a, b: type(a)(
  577. [
  578. *a.items,
  579. *b.items,
  580. ]
  581. ),
  582. ),
  583. ]
  584. op_handlers[operator.add].extend(list_like_addition_handlers)
  585. def list_iadd_handler(tx: "InstructionTranslator", a, b):
  586. if a.is_immutable() or not b.has_unpack_var_sequence(tx):
  587. # Handler doesn't apply
  588. return None
  589. seq = b.unpack_var_sequence(tx)
  590. tx.output.side_effects.mutation(a)
  591. a.items.extend(seq)
  592. return a
  593. list_like_iadd_handlers: list[
  594. tuple[
  595. tuple[type[VariableTracker], type[VariableTracker]],
  596. _HandlerCallback,
  597. ]
  598. ] = [
  599. (
  600. (ListVariable, VariableTracker),
  601. list_iadd_handler,
  602. ),
  603. (
  604. (TupleVariable, TupleVariable),
  605. tuple_add_handler,
  606. ),
  607. (
  608. (TupleVariable, ConstantVariable),
  609. tuple_add_handler,
  610. ),
  611. ]
  612. op_handlers[operator.iadd].extend(list_like_iadd_handlers)
  613. # List-like expansion (e.g. [1, 2, 3] * 3)
  614. def expand_list_like(tx: "InstructionTranslator", lst, const):
  615. if isinstance(lst, ConstantVariable):
  616. lst, const = const, lst
  617. try:
  618. return lst.__class__(
  619. items=lst.items * const.as_python_constant(),
  620. mutation_type=ValueMutationNew(),
  621. )
  622. except MemoryError as exc:
  623. raise_observed_exception(
  624. type(exc),
  625. tx,
  626. args=list(map(ConstantVariable.create, exc.args)),
  627. )
  628. list_like_expansion_handlers: list[
  629. tuple[
  630. tuple[type[VariableTracker], type[VariableTracker]],
  631. _HandlerCallback,
  632. ]
  633. ] = [
  634. ((ListVariable, ConstantVariable), expand_list_like),
  635. ((TupleVariable, ConstantVariable), expand_list_like),
  636. ((ConstantVariable, ListVariable), expand_list_like),
  637. ((ConstantVariable, TupleVariable), expand_list_like),
  638. ]
  639. op_handlers[operator.mul].extend(list_like_expansion_handlers)
  640. def create_cmp_op_handlers(op):
  641. def compare_by_value(tx: "InstructionTranslator", a, b):
  642. try:
  643. return ConstantVariable(op(a.value, b.value))
  644. except TypeError as exc:
  645. raise_observed_exception(
  646. type(exc),
  647. tx,
  648. args=list(map(ConstantVariable.create, exc.args)),
  649. )
  650. result: list[
  651. tuple[
  652. tuple[
  653. _TrackersType,
  654. _TrackersType,
  655. ],
  656. _HandlerCallback,
  657. ]
  658. ] = [((ConstantVariable, ConstantVariable), compare_by_value)]
  659. if op in polyfill_fn_mapping:
  660. # For constants, speedup the comparison instead of using
  661. # polyfill. Removing this line causes major regression for pr
  662. # time benchmark - add_loop_eager.
  663. result = [((ConstantVariable, ConstantVariable), compare_by_value)]
  664. op_var = BuiltinVariable(op)
  665. # Special handling of SymNode variable
  666. result.extend(
  667. [
  668. (
  669. (SymNodeVariable, VariableTracker),
  670. op_var._comparison_with_symnode,
  671. ),
  672. (
  673. (VariableTracker, SymNodeVariable),
  674. op_var._comparison_with_symnode,
  675. ),
  676. ]
  677. )
  678. def handler(tx, a, b):
  679. return tx.inline_user_function_return(
  680. VariableTracker.build(tx, polyfill_fn_mapping[op]), [a, b], {}
  681. )
  682. result.append(((VariableTracker, VariableTracker), handler))
  683. return result
  684. result = [((ConstantVariable, ConstantVariable), compare_by_value)]
  685. if op in supported_const_comparison_ops.values() and op.__name__.startswith(
  686. "is_"
  687. ):
  688. # Tensor is None, List is not None, etc
  689. none_result = op(object(), None)
  690. def never(tx: "InstructionTranslator", a, b):
  691. return ConstantVariable(none_result)
  692. obj_op_none = never
  693. none_op_obj = never
  694. types_that_are_never_none = (
  695. TensorVariable,
  696. SymNodeVariable,
  697. NNModuleVariable,
  698. BaseListVariable,
  699. UserDefinedVariable,
  700. BaseUserFunctionVariable,
  701. ConstDictVariable,
  702. BaseTorchVariable,
  703. )
  704. result.extend(
  705. [
  706. (
  707. (types_that_are_never_none, ConstantVariable),
  708. obj_op_none,
  709. ),
  710. (
  711. (ConstantVariable, types_that_are_never_none),
  712. none_op_obj,
  713. ),
  714. ]
  715. )
  716. op_var = BuiltinVariable(op)
  717. result.extend(
  718. [
  719. (
  720. (
  721. (UserFunctionVariable, BuiltinVariable),
  722. (UserFunctionVariable, BuiltinVariable),
  723. ),
  724. lambda tx, a, b: ConstantVariable(op(a.fn, b.fn)),
  725. ),
  726. (
  727. (
  728. NNModuleVariable,
  729. NNModuleVariable,
  730. ),
  731. lambda tx, a, b: ConstantVariable(
  732. op(
  733. tx.output.get_submodule(a.module_key),
  734. tx.output.get_submodule(b.module_key),
  735. )
  736. ),
  737. ),
  738. (
  739. (UserDefinedObjectVariable, UserDefinedObjectVariable),
  740. compare_by_value,
  741. ),
  742. (
  743. (UserDefinedClassVariable, UserDefinedClassVariable),
  744. compare_by_value,
  745. ),
  746. (
  747. (
  748. (StreamVariable, EventVariable, ConstantVariable),
  749. (StreamVariable, EventVariable, ConstantVariable),
  750. ),
  751. compare_by_value,
  752. ),
  753. (
  754. (TensorVariable, VariableTracker),
  755. op_var._comparison_with_tensor,
  756. ),
  757. (
  758. (VariableTracker, TensorVariable),
  759. op_var._comparison_with_tensor,
  760. ),
  761. (
  762. (SymNodeVariable, VariableTracker),
  763. op_var._comparison_with_symnode,
  764. ),
  765. (
  766. (VariableTracker, SymNodeVariable),
  767. op_var._comparison_with_symnode,
  768. ),
  769. ]
  770. )
  771. def handle_is(tx: "InstructionTranslator", left, right):
  772. # If the two objects are of different type, we can safely return False
  773. # and True for `is` and `is not`, respectively
  774. if type(left) is not type(right):
  775. return ConstantVariable.create(op.__name__ != "is_")
  776. if left is right:
  777. return ConstantVariable.create(op(left, right))
  778. if (
  779. istype(left, variables.ExceptionVariable)
  780. and istype(right, variables.ExceptionVariable)
  781. and left.exc_type is not right.exc_type
  782. ):
  783. return ConstantVariable.create(op(left, right))
  784. result.append(((VariableTracker, VariableTracker), handle_is))
  785. return result
  786. for op in supported_comparison_ops.values():
  787. assert callable(op)
  788. assert op not in op_handlers
  789. op_handlers[op] = create_cmp_op_handlers(op)
  790. return op_handlers
  791. @staticmethod
  792. def _find_binop_handler(op, a_type, b_type):
  793. handlers = BuiltinVariable._binop_handlers().get(op)
  794. if handlers is None:
  795. return None
  796. matches = []
  797. for (type1, type2), handler in handlers:
  798. if issubclass(a_type, type1) and issubclass(b_type, type2):
  799. matches.append(handler)
  800. return matches
  801. def can_insert_in_graph(self):
  802. return self.fn in self._fx_graph_functions()
  803. def __init__(self, fn, **kwargs) -> None:
  804. super().__init__(**kwargs)
  805. self.fn = fn
  806. def __repr__(self) -> str:
  807. if self.fn is None:
  808. name = "None"
  809. else:
  810. name = self.fn.__name__
  811. return f"{self.__class__.__name__}({name})"
  812. def as_python_constant(self):
  813. return self.fn
  814. def as_proxy(self):
  815. DTYPE = {
  816. bool: torch.bool,
  817. int: torch.int64,
  818. float: torch.float64,
  819. }
  820. if self.fn in DTYPE:
  821. return DTYPE[self.fn]
  822. return super().as_proxy()
  823. def reconstruct(self, codegen: "PyCodegen"):
  824. name = self.fn.__name__
  825. assert self.fn.__module__ == "builtins"
  826. assert name not in codegen.tx.f_globals, "shadowed global"
  827. codegen.append_output(codegen.create_load_global(name, add=True))
  828. def constant_args(self, *args, **kwargs):
  829. return check_constant_args(args, kwargs)
  830. def tensor_args(self, *args):
  831. any_tensor = False
  832. for arg in args:
  833. if isinstance(arg, variables.GetAttrVariable):
  834. return False
  835. any_tensor = any_tensor or isinstance(arg, variables.TensorVariable)
  836. return any_tensor
  837. def tensor_args_type(self, arg_types):
  838. any_tensor = False
  839. for arg_type in arg_types:
  840. if issubclass(arg_type, variables.GetAttrVariable):
  841. return False
  842. any_tensor = any_tensor or issubclass(arg_type, variables.TensorVariable)
  843. return any_tensor
  844. def python_and_tensor_constant_only(self, *args, **kwargs):
  845. tensor_args = []
  846. non_tensor_args = []
  847. for i in itertools.chain(args, kwargs.values()):
  848. if isinstance(i, variables.TensorVariable):
  849. tensor_args.append(i)
  850. else:
  851. non_tensor_args.append(i)
  852. return all(
  853. is_constant_source(t.source) if t.source is not None else False
  854. for t in tensor_args
  855. ) and self.constant_args(*non_tensor_args)
  856. @staticmethod
  857. def unwrap_unspec_args_kwargs(args, kwargs):
  858. return [x.as_python_constant() for x in args], {
  859. k: v.as_python_constant() for k, v in kwargs.items()
  860. }
  861. def has_constant_handler(self, args, kwargs):
  862. return self.can_constant_fold_through() and check_unspec_or_constant_args(
  863. args, kwargs
  864. )
  865. @staticmethod
  866. def _make_handler(fn, arg_types: list[type], has_kwargs: bool):
  867. from .lazy import LazyVariableTracker
  868. obj = BuiltinVariable(fn)
  869. handlers: list[_HandlerCallback] = []
  870. if any(issubclass(t, LazyVariableTracker) for t in arg_types):
  871. return lambda tx, args, kwargs: obj.call_function(
  872. tx, [v.realize() for v in args], kwargs
  873. )
  874. if inspect.isclass(fn) and (
  875. issubclass(fn, Exception)
  876. # GeneratorExit doesn't inherit from Exception
  877. # >>> issubclass(GeneratorExit, Exception)
  878. # False
  879. or fn is GeneratorExit
  880. ):
  881. def create_exception_class_object(
  882. tx: "InstructionTranslator", args, kwargs
  883. ):
  884. if fn is AssertionError and not all(
  885. isinstance(x, variables.ConstantVariable)
  886. and isinstance(x.value, str)
  887. for x in args
  888. ):
  889. unimplemented_v2(
  890. gb_type="assert with non-string message",
  891. context=str(args),
  892. explanation="Dynamo only supports asserts with string messages",
  893. hints=[*graph_break_hints.SUPPORTABLE],
  894. )
  895. return variables.ExceptionVariable(fn, args, **kwargs)
  896. return create_exception_class_object
  897. if obj.can_insert_in_graph() and not (
  898. fn is operator.getitem
  899. and not issubclass(arg_types[0], variables.TensorVariable)
  900. ):
  901. if obj.tensor_args_type(arg_types):
  902. return obj._handle_insert_op_in_graph
  903. elif has_kwargs:
  904. # need runtime check for kwargs
  905. handlers.append(obj._handle_insert_op_in_graph)
  906. # Handle binary ops (e.g. __add__ / __radd__, __iadd__, etc.)
  907. # NB: Tensor args are handled above and not here
  908. if len(arg_types) == 2 and not has_kwargs:
  909. # Try to find a handler for the arg types; otherwise, fall through to constant handler
  910. binop_handlers = BuiltinVariable._find_binop_handler(fn, *arg_types)
  911. if not binop_handlers:
  912. pass
  913. elif len(binop_handlers) == 1:
  914. (binop_handler,) = binop_handlers
  915. handlers.append(lambda tx, args, _: binop_handler(tx, *args))
  916. else:
  917. def call_binop_handlers(tx: "InstructionTranslator", args, _):
  918. for fn in binop_handlers:
  919. rv = fn(tx, *args)
  920. if rv:
  921. return rv
  922. handlers.append(call_binop_handlers)
  923. self_handler = getattr(obj, f"call_{fn.__name__}", None)
  924. if self_handler:
  925. def call_self_handler(tx: "InstructionTranslator", args, kwargs):
  926. try:
  927. result = self_handler(tx, *args, **kwargs)
  928. if result is not None:
  929. return result
  930. except TypeError:
  931. # Check if binding is bad. inspect signature bind is expensive.
  932. # So check only when handler call fails.
  933. try:
  934. inspect.signature(self_handler).bind(tx, *args, **kwargs)
  935. except TypeError as e:
  936. has_constant_handler = obj.has_constant_handler(args, kwargs)
  937. if not has_constant_handler:
  938. log.warning(
  939. "incorrect arg count %s %s and no constant handler",
  940. self_handler,
  941. e,
  942. )
  943. unimplemented_v2(
  944. gb_type="invalid call to builtin op handler",
  945. context=f"invalid args to {self_handler}: {args} {kwargs}",
  946. explanation=f"Encountered TypeError when trying to handle op {fn.__name__}",
  947. hints=[*graph_break_hints.DIFFICULT],
  948. )
  949. else:
  950. raise
  951. except Unsupported as exc:
  952. has_constant_handler = obj.has_constant_handler(args, kwargs)
  953. if not has_constant_handler:
  954. raise
  955. # Actually, we will handle this just fine
  956. exc.remove_from_stats()
  957. handlers.append(call_self_handler)
  958. if obj.can_constant_fold_through():
  959. if (
  960. all(issubclass(x, ConstantVariable) for x in arg_types)
  961. and not has_kwargs
  962. ):
  963. def constant_fold_handler(tx: "InstructionTranslator", args, kwargs):
  964. # fast path
  965. try:
  966. res = fn(
  967. *[x.as_python_constant() for x in args],
  968. )
  969. except Exception as exc:
  970. raise_observed_exception(
  971. type(exc),
  972. tx,
  973. args=list(map(ConstantVariable.create, exc.args)),
  974. )
  975. except AsPythonConstantNotImplementedError as exc:
  976. unimplemented_v2(
  977. gb_type="constant fold exception",
  978. context=f"attempted to run function {fn} with arguments {args}",
  979. explanation="Encountered exception when attempting to constant fold.",
  980. hints=[*graph_break_hints.DYNAMO_BUG],
  981. from_exc=exc,
  982. )
  983. return VariableTracker.build(tx, res)
  984. else:
  985. def constant_fold_handler(tx: "InstructionTranslator", args, kwargs):
  986. # path with a runtime check
  987. if check_unspec_or_constant_args(args, kwargs):
  988. try:
  989. res = fn(
  990. *[x.as_python_constant() for x in args],
  991. **{
  992. k: v.as_python_constant() for k, v in kwargs.items()
  993. },
  994. )
  995. except AsPythonConstantNotImplementedError as exc:
  996. unimplemented_v2(
  997. gb_type="constant fold exception",
  998. context=f"attempted to run function {fn} with arguments {args}",
  999. explanation="Encountered exception when attempting to constant fold.",
  1000. hints=[*graph_break_hints.DYNAMO_BUG],
  1001. from_exc=exc,
  1002. )
  1003. except Exception as exc:
  1004. raise_observed_exception(
  1005. type(exc),
  1006. tx,
  1007. args=list(map(ConstantVariable.create, exc.args)),
  1008. )
  1009. return VariableTracker.build(tx, res)
  1010. handlers.append(constant_fold_handler)
  1011. def call_unimplemented_v2(args):
  1012. real_arg_types = [arg.python_type_name() for arg in args]
  1013. unimplemented_v2(
  1014. gb_type="Failed to trace builtin operator",
  1015. context=f"builtin {fn.__name__} {arg_types} {has_kwargs}",
  1016. explanation=f"Dynamo does not know how to trace builtin operator `{fn.__name__}` "
  1017. f"with argument types {real_arg_types} (has_kwargs {has_kwargs})",
  1018. hints=[
  1019. f"Avoid calling builtin `{fn.__name__}` with argument types {real_arg_types}. "
  1020. f"Consider using an equivalent alternative function/method to `{fn.__name__}`.",
  1021. "If you are attempting to call a logging function (e.g. `print`), "
  1022. "you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.",
  1023. "Please report an issue to PyTorch.",
  1024. ],
  1025. )
  1026. if len(handlers) == 0:
  1027. return lambda tx, args, kwargs: call_unimplemented_v2(args)
  1028. elif len(handlers) == 1:
  1029. (handler,) = handlers
  1030. def builtin_dispatch(tx: "InstructionTranslator", args, kwargs):
  1031. rv = handler(tx, args, kwargs)
  1032. if rv:
  1033. return rv
  1034. call_unimplemented_v2(args)
  1035. else:
  1036. def builtin_dispatch(tx: "InstructionTranslator", args, kwargs):
  1037. for fn in handlers:
  1038. rv = fn(tx, args, kwargs)
  1039. if rv:
  1040. return rv
  1041. call_unimplemented_v2(args)
  1042. return builtin_dispatch
  1043. def call_vars(self, tx: "InstructionTranslator", *args):
  1044. if len(args) == 0:
  1045. unimplemented_v2(
  1046. gb_type="unimplemented builtin op vars() with no arguments",
  1047. context=f"vars: {self} {args}",
  1048. explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with no arguments",
  1049. hints=[*graph_break_hints.SUPPORTABLE],
  1050. )
  1051. assert len(args) == 1
  1052. # vars(obj) is obj.__dict__ if __dict__ is present else TypeError
  1053. try:
  1054. return args[0].var_getattr(tx, "__dict__")
  1055. except ObservedAttributeError:
  1056. raise_observed_exception(TypeError, tx)
  1057. def _handle_insert_op_in_graph(self, tx: "InstructionTranslator", args, kwargs):
  1058. from .builder import wrap_fx_proxy, wrap_fx_proxy_cls
  1059. if kwargs and not self.tensor_args(*args, *kwargs.values()):
  1060. return
  1061. # insert handling for torch function here
  1062. from .builder import SourcelessBuilder
  1063. from .torch_function import can_dispatch_torch_function, dispatch_torch_function
  1064. global BUILTIN_TO_TENSOR_RFN_MAP, BUILTIN_TO_TENSOR_FN_MAP
  1065. if can_dispatch_torch_function(tx, args, kwargs):
  1066. # Only remap the fn to tensor methods if we aren't exporting
  1067. # export serde does not handle method descriptors today
  1068. if not tx.export:
  1069. # Ensure the builtin maps are populated before accessing them
  1070. populate_builtin_to_tensor_fn_map()
  1071. # Use sourceless builder, we built the map ourselves
  1072. if not isinstance(args[0], TensorVariable):
  1073. if self.fn in BUILTIN_TO_TENSOR_RFN_MAP:
  1074. func = BUILTIN_TO_TENSOR_RFN_MAP[self.fn]
  1075. else:
  1076. func = BUILTIN_TO_TENSOR_FN_MAP[self.fn]
  1077. tmp = args[0]
  1078. # swap args and call reverse version of func
  1079. args[0] = args[1]
  1080. args[1] = tmp
  1081. else:
  1082. func = BUILTIN_TO_TENSOR_FN_MAP[self.fn]
  1083. else:
  1084. func = self.fn
  1085. fn_var = SourcelessBuilder.create(tx, func)
  1086. return dispatch_torch_function(tx, fn_var, args, kwargs)
  1087. fn = self.fn
  1088. try:
  1089. # Constant fold for constant tensor and python constants
  1090. if self.python_and_tensor_constant_only(*args, **kwargs):
  1091. from ..bytecode_transformation import unique_id
  1092. from .functions import invoke_and_store_as_constant
  1093. return invoke_and_store_as_constant(
  1094. tx, fn, unique_id(fn.__name__), args, kwargs
  1095. )
  1096. if fn in IN_PLACE_DESUGARING_MAP and isinstance(
  1097. args[0], variables.ConstantVariable
  1098. ):
  1099. # In-place operators like += usually mustate tensor
  1100. # values, but in the edge case of immutable values they
  1101. # re-bind the variable.
  1102. #
  1103. # The easiest way to keep the graph consistent in this
  1104. # scenario is to de-sugar eagerly.
  1105. fn, args = IN_PLACE_DESUGARING_MAP[fn], [args[0], args[1]]
  1106. if fn is operator.getitem and isinstance(args[1], SymNodeVariable):
  1107. # Standard indexing will force specialization due to
  1108. # __index__. Rewrite as a regular torch op which will
  1109. # trace fine
  1110. fn, args = (
  1111. torch.select,
  1112. [
  1113. args[0],
  1114. variables.ConstantVariable.create(0),
  1115. args[1],
  1116. ],
  1117. )
  1118. # Interaction between ndarray and tensors:
  1119. # We prefer the tensor op whenever there are tensors involved
  1120. if check_numpy_ndarray_args(args, kwargs) and not any(
  1121. type(arg) == variables.TensorVariable for arg in args
  1122. ):
  1123. proxy = tx.output.create_proxy(
  1124. "call_function",
  1125. numpy_operator_wrapper(fn),
  1126. *proxy_args_kwargs(args, kwargs),
  1127. )
  1128. return wrap_fx_proxy_cls(variables.NumpyNdarrayVariable, tx, proxy)
  1129. if (
  1130. fn is operator.eq
  1131. and len(args) == 2
  1132. and isinstance(args[0], variables.TensorVariable)
  1133. ):
  1134. # Dynamo expects `__eq__` str while operator.eq gives just `eq`
  1135. # TODO - supporting all comparison operators could also work but
  1136. # it fails lots of tests because graph str changes.
  1137. return args[0].call_method(tx, "__eq__", args[1:], kwargs)
  1138. proxy = tx.output.create_proxy(
  1139. "call_function",
  1140. fn,
  1141. *proxy_args_kwargs(args, kwargs),
  1142. )
  1143. if any(isinstance(arg, FakeItemVariable) for arg in args):
  1144. return wrap_fx_proxy_cls(
  1145. FakeItemVariable,
  1146. tx,
  1147. proxy,
  1148. )
  1149. elif check_unspec_python_args(args, kwargs):
  1150. _args, _kwargs = self.unwrap_unspec_args_kwargs(args, kwargs)
  1151. raw_value = fn(*_args, **_kwargs)
  1152. need_unwrap = any(
  1153. x.need_unwrap
  1154. for x in itertools.chain(args, kwargs.values())
  1155. if isinstance(x, variables.UnspecializedPythonVariable)
  1156. )
  1157. return wrap_fx_proxy_cls(
  1158. UnspecializedPythonVariable,
  1159. tx,
  1160. proxy,
  1161. raw_value=raw_value,
  1162. need_unwrap=need_unwrap,
  1163. )
  1164. elif all(isinstance(x, SymNodeVariable) for x in args):
  1165. return SymNodeVariable.create(tx, proxy, None)
  1166. else:
  1167. # Work around for vision_maskrcnn due to precision difference
  1168. # specialize the dividend when float divide by tensor
  1169. if fn is operator.truediv and isinstance(
  1170. args[0], variables.UnspecializedPythonVariable
  1171. ):
  1172. args[0] = args[0].as_python_constant()
  1173. return wrap_fx_proxy(tx, proxy)
  1174. except NotImplementedError:
  1175. unimplemented_v2(
  1176. gb_type="unimplemented builtin op on tensor arguments",
  1177. context=f"partial tensor op: {self} {args} {kwargs}",
  1178. explanation=f"Dynamo does not know how to trace builtin operator {self.fn} with tensor arguments",
  1179. hints=[*graph_break_hints.SUPPORTABLE],
  1180. )
  1181. call_function_handler_cache: dict[
  1182. tuple[object, ...],
  1183. Callable[
  1184. [
  1185. "InstructionTranslator",
  1186. Sequence[VariableTracker],
  1187. dict[str, VariableTracker],
  1188. ],
  1189. VariableTracker,
  1190. ],
  1191. ] = {}
  1192. def call_function(
  1193. self,
  1194. tx: "InstructionTranslator",
  1195. args: Sequence["VariableTracker"],
  1196. kwargs: "dict[str, VariableTracker]",
  1197. ) -> "VariableTracker":
  1198. key: tuple[object, ...]
  1199. if kwargs:
  1200. kwargs = {k: v.realize() for k, v in kwargs.items()}
  1201. key = (self.fn, *(type(x) for x in args), True)
  1202. else:
  1203. key = (self.fn, *(type(x) for x in args))
  1204. handler = self.call_function_handler_cache.get(key)
  1205. if not handler:
  1206. self.call_function_handler_cache[key] = handler = self._make_handler(
  1207. self.fn, [type(x) for x in args], bool(kwargs)
  1208. )
  1209. return handler(tx, args, kwargs)
  1210. def call_method(
  1211. self,
  1212. tx,
  1213. name,
  1214. args: "list[VariableTracker]",
  1215. kwargs: "dict[str, VariableTracker]",
  1216. ) -> "VariableTracker":
  1217. if self.fn is object and name == "__setattr__":
  1218. assert len(args) == 3
  1219. assert len(kwargs) == 0
  1220. obj, name_var, val = args
  1221. obj = obj.realize()
  1222. if (
  1223. isinstance(obj, UserDefinedObjectVariable)
  1224. and tx.output.side_effects.is_attribute_mutation(obj)
  1225. and name_var.is_python_constant()
  1226. ):
  1227. return obj.method_setattr_standard(tx, name_var, val)
  1228. if name == "__new__":
  1229. # Supported __new__ methods
  1230. if self.fn is object and len(args) == 1:
  1231. assert len(kwargs) == 0
  1232. return tx.output.side_effects.track_new_user_defined_object(
  1233. self, args[0], args[1:]
  1234. )
  1235. if self.fn is dict and len(args) == 1 and not kwargs:
  1236. dict_vt = ConstDictVariable({}, dict, mutation_type=ValueMutationNew())
  1237. if isinstance(args[0], BuiltinVariable) and args[0].fn is dict:
  1238. return dict_vt
  1239. # We don't have to set the underlying dict_vt in
  1240. # UserDefinedDictVariable because it will be set to empty
  1241. # ConstDictVariableTracker in the constructor.
  1242. return tx.output.side_effects.track_new_user_defined_object(
  1243. self,
  1244. args[0],
  1245. args[1:],
  1246. )
  1247. if (
  1248. self.fn is tuple
  1249. and len(args) == 2
  1250. and args[1].has_force_unpack_var_sequence(tx)
  1251. and not kwargs
  1252. ):
  1253. if isinstance(args[0], BuiltinVariable) and args[0].fn is tuple:
  1254. init_args = args[1].force_unpack_var_sequence(tx)
  1255. return variables.TupleVariable(
  1256. init_args, mutation_type=ValueMutationNew()
  1257. )
  1258. return tx.output.side_effects.track_new_user_defined_object(
  1259. self,
  1260. args[0],
  1261. args[1:],
  1262. )
  1263. if self.fn is list:
  1264. list_vt = ListVariable([], mutation_type=ValueMutationNew())
  1265. if isinstance(args[0], BuiltinVariable) and args[0].fn is list:
  1266. return list_vt
  1267. return tx.output.side_effects.track_new_user_defined_object(
  1268. self,
  1269. args[0],
  1270. args[1:],
  1271. )
  1272. if self.fn is float and len(args) == 1 and name in ("fromhex", "hex"):
  1273. if isinstance(args[0], ConstantVariable):
  1274. try:
  1275. fn = getattr(float, name)
  1276. res = fn(args[0].as_python_constant())
  1277. return variables.ConstantVariable.create(res)
  1278. except (OverflowError, ValueError) as e:
  1279. raise_observed_exception(
  1280. type(e),
  1281. tx,
  1282. args=list(map(ConstantVariable.create, e.args)),
  1283. )
  1284. if self.fn is object and name == "__init__":
  1285. # object.__init__ is a no-op
  1286. return variables.ConstantVariable(None)
  1287. if self.fn is dict and name == "fromkeys":
  1288. return BuiltinVariable.call_custom_dict_fromkeys(tx, dict, *args, **kwargs)
  1289. if self.fn is dict:
  1290. resolved_fn = getattr(self.fn, name)
  1291. if resolved_fn in dict_methods:
  1292. if isinstance(args[0], variables.UserDefinedDictVariable):
  1293. return args[0]._dict_vt.call_method(tx, name, args[1:], kwargs)
  1294. elif isinstance(args[0], variables.ConstDictVariable):
  1295. return args[0].call_method(tx, name, args[1:], kwargs)
  1296. if self.fn is set:
  1297. resolved_fn = getattr(self.fn, name)
  1298. if resolved_fn in set_methods:
  1299. if isinstance(args[0], variables.UserDefinedSetVariable):
  1300. return args[0]._set_vt.call_method(tx, name, args[1:], kwargs)
  1301. elif isinstance(args[0], variables.SetVariable):
  1302. return args[0].call_method(tx, name, args[1:], kwargs)
  1303. if self.fn is frozenset:
  1304. resolved_fn = getattr(self.fn, name)
  1305. if resolved_fn in frozenset_methods:
  1306. if isinstance(args[0], variables.FrozensetVariable):
  1307. return args[0].call_method(tx, name, args[1:], kwargs)
  1308. if self.fn is str and len(args) >= 1:
  1309. resolved_fn = getattr(self.fn, name)
  1310. if resolved_fn in str_methods:
  1311. if isinstance(args[0], ConstantVariable):
  1312. return args[0].call_method(tx, name, args[1:], kwargs)
  1313. if self.fn is float and len(args) >= 1:
  1314. if isinstance(args[0], ConstantVariable):
  1315. return ConstantVariable.create(
  1316. getattr(float, name)(args[0].as_python_constant())
  1317. )
  1318. return super().call_method(tx, name, args, kwargs)
  1319. def _call_int_float(self, tx: "InstructionTranslator", arg):
  1320. # Handle cases like int(torch.seed())
  1321. # Also handle sym_float to sym_int cases
  1322. if isinstance(arg, (SymNodeVariable, variables.TensorVariable)):
  1323. if isinstance(arg, variables.TensorVariable):
  1324. item = arg.call_method(tx, "item", [], {})
  1325. else:
  1326. item = arg
  1327. fn_ = sym_int if self.fn is int else sym_float
  1328. from torch._dynamo.variables.builder import wrap_fx_proxy
  1329. return wrap_fx_proxy(
  1330. tx=tx,
  1331. proxy=tx.output.create_proxy(
  1332. "call_function",
  1333. fn_,
  1334. (item.as_proxy(),),
  1335. {},
  1336. ),
  1337. )
  1338. call_int = _call_int_float
  1339. call_float = _call_int_float
  1340. def call_bool(self, tx: "InstructionTranslator", arg):
  1341. # Emulate `PyBool_Type.tp_vectorcall` which boils down to `PyObject_IsTrue`.
  1342. # https://github.com/python/cpython/blob/3.12/Objects/object.c#L1674-L1697
  1343. if isinstance(arg, SymNodeVariable):
  1344. # Note that we delay specializing on symbolic values to avoid
  1345. # unnecessary guards. Specialization will happen later if, e.g., the
  1346. # resulting boolean is used for branching.
  1347. if isinstance(arg.sym_num, torch.SymBool):
  1348. return arg
  1349. # Emulate `nb_bool` of int/float objects
  1350. # - https://github.com/python/cpython/blob/3.12/Objects/longobject.c#L4940-L4944
  1351. # - https://github.com/python/cpython/blob/3.12/Objects/floatobject.c#L878-L882
  1352. assert istype(arg.sym_num, (torch.SymInt, torch.SymFloat))
  1353. return SymNodeVariable.create(tx, arg.as_proxy() != 0)
  1354. # TODO handle more cases and merge this with this with `generic_jump`.
  1355. def call_str(self, tx: "InstructionTranslator", arg):
  1356. # Handle `str` on a user defined function or object
  1357. if isinstance(arg, (variables.UserFunctionVariable)):
  1358. return variables.ConstantVariable.create(value=str(arg.fn))
  1359. elif isinstance(arg, (variables.UserDefinedObjectVariable)):
  1360. # Check if object has __str__ method
  1361. if hasattr(arg.value, "__str__"):
  1362. str_method = arg.value.__str__
  1363. elif hasattr(arg.value, "__repr__"):
  1364. # account for __repr__ functions when __str__ is absent
  1365. str_method = arg.value.__repr__
  1366. else:
  1367. unimplemented_v2(
  1368. gb_type="failed to call str() on user defined object",
  1369. context=str(arg),
  1370. explanation="User defined object has no __str__ or __repr__ method",
  1371. hints=[*graph_break_hints.USER_ERROR],
  1372. )
  1373. if type(arg.value).__str__ is object.__str__:
  1374. # Rely on the object str method
  1375. try:
  1376. return variables.ConstantVariable.create(value=str_method())
  1377. except AttributeError:
  1378. # Graph break
  1379. return
  1380. elif is_wrapper_or_member_descriptor(str_method):
  1381. unimplemented_v2(
  1382. gb_type="Attempted to a str() method implemented in C/C++",
  1383. context="",
  1384. explanation=f"{type(arg.value)} has a C/C++ based str method. This is not supported.",
  1385. hints=["Write the str method in Python"],
  1386. )
  1387. else:
  1388. # Overrides for custom str method
  1389. # Pass method as function to call tx.inline_user_function_return
  1390. bound_method = str_method.__func__ # type: ignore[attr-defined]
  1391. try:
  1392. # Only supports certain function types
  1393. user_func_variable = variables.UserFunctionVariable(bound_method)
  1394. except AssertionError as e:
  1395. # Won't be able to do inline the str method, return to avoid graph break
  1396. log.warning("Failed to create UserFunctionVariable: %s", e)
  1397. return
  1398. # Inline the user function
  1399. return tx.inline_user_function_return(user_func_variable, [arg], {})
  1400. elif isinstance(arg, (variables.ExceptionVariable,)):
  1401. if len(arg.args) == 0:
  1402. value = f"{arg.exc_type}"
  1403. else:
  1404. value = ", ".join(a.as_python_constant() for a in arg.args)
  1405. return variables.ConstantVariable.create(value=value)
  1406. def _call_min_max(self, tx: "InstructionTranslator", *args):
  1407. if len(args) == 1 and args[0].has_force_unpack_var_sequence(tx):
  1408. items = args[0].force_unpack_var_sequence(tx)
  1409. return self._call_min_max_seq(tx, items)
  1410. elif len(args) == 2:
  1411. return self._call_min_max_binary(tx, args[0], args[1])
  1412. elif len(args) > 2:
  1413. return self._call_min_max_seq(tx, args)
  1414. def _call_min_max_seq(self, tx: "InstructionTranslator", items):
  1415. assert len(items) > 0
  1416. if len(items) == 1:
  1417. return items[0]
  1418. return functools.reduce(functools.partial(self._call_min_max_binary, tx), items)
  1419. def _call_min_max_binary(self, tx: "InstructionTranslator", a, b):
  1420. if a is None or b is None:
  1421. # a or b could be none if we reduce and _call_min_max_binary failed
  1422. # to return something
  1423. return
  1424. if self.tensor_args(a, b):
  1425. if not isinstance(a, variables.TensorVariable):
  1426. a, b = b, a
  1427. assert isinstance(a, variables.TensorVariable)
  1428. # result of an item call is a scalar convert to a tensor
  1429. if isinstance(a, FakeItemVariable):
  1430. a = variables.TorchInGraphFunctionVariable(torch.tensor).call_function(
  1431. tx, [a], {}
  1432. )
  1433. # Dynamic input does not get resolved, rather, gets stored as call_function
  1434. if isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable):
  1435. from .builder import wrap_fx_proxy_cls
  1436. return wrap_fx_proxy_cls(
  1437. type(a),
  1438. tx=tx,
  1439. proxy=tx.output.create_proxy(
  1440. "call_function",
  1441. self.fn,
  1442. *proxy_args_kwargs([a, b], {}),
  1443. ),
  1444. )
  1445. # convert min/max to torch ops
  1446. if b.is_python_constant():
  1447. fn: VariableTracker
  1448. if isinstance(a, variables.NumpyNdarrayVariable):
  1449. import numpy as np
  1450. fn = variables.NumpyVariable(np.clip)
  1451. else:
  1452. fn = variables.TorchInGraphFunctionVariable(torch.clamp)
  1453. kwargs = {"min": b} if (self.fn is max) else {"max": b}
  1454. result = fn.call_function(tx, [a], kwargs)
  1455. else:
  1456. if isinstance(a, variables.NumpyNdarrayVariable):
  1457. import numpy as np
  1458. np_fn = {max: np.maximum, min: np.minimum}[self.fn]
  1459. fn = variables.NumpyVariable(np_fn)
  1460. else:
  1461. torch_fn = {max: torch.maximum, min: torch.minimum}[self.fn]
  1462. fn = variables.TorchInGraphFunctionVariable(torch_fn)
  1463. result = fn.call_function(tx, [a, b], {})
  1464. # return unspec if both a, b are unspec or const
  1465. if all(
  1466. isinstance(
  1467. i,
  1468. (
  1469. variables.UnspecializedPythonVariable,
  1470. variables.ConstantVariable,
  1471. ),
  1472. )
  1473. for i in [a, b]
  1474. ):
  1475. if any(isinstance(val, FakeItemVariable) for val in [a, b]):
  1476. return variables.FakeItemVariable.from_tensor_variable(result)
  1477. if b.is_python_constant():
  1478. raw_b = b.as_python_constant()
  1479. else:
  1480. raw_b = b.raw_value
  1481. if self.fn is max:
  1482. raw_res = max(a.raw_value, raw_b)
  1483. else:
  1484. raw_res = min(a.raw_value, raw_b)
  1485. need_unwrap = any(
  1486. x.need_unwrap
  1487. for x in [a, b]
  1488. if isinstance(x, variables.UnspecializedPythonVariable)
  1489. )
  1490. return variables.UnspecializedPythonVariable.from_tensor_variable(
  1491. result, raw_res, need_unwrap
  1492. )
  1493. # otherwise return tensor
  1494. else:
  1495. return result
  1496. elif isinstance(a, SymNodeVariable) or isinstance(b, SymNodeVariable):
  1497. py_fn = torch.sym_max if self.fn is max else torch.sym_min
  1498. proxy = tx.output.create_proxy(
  1499. "call_function", py_fn, *proxy_args_kwargs([a, b], {})
  1500. )
  1501. return SymNodeVariable.create(tx, proxy, None)
  1502. elif isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
  1503. value = self.fn(
  1504. a.as_python_constant(),
  1505. b.as_python_constant(),
  1506. )
  1507. return ConstantVariable(value)
  1508. call_min = _call_min_max
  1509. call_max = _call_min_max
  1510. def call_abs(self, tx: "InstructionTranslator", arg: "VariableTracker"):
  1511. # Call arg.__abs__()
  1512. abs_method = BuiltinVariable(getattr).call_function(
  1513. tx, [arg, ConstantVariable.create("__abs__")], {}
  1514. )
  1515. return abs_method.call_function(tx, [], {})
  1516. def call_pos(self, tx: "InstructionTranslator", arg: "VariableTracker"):
  1517. # Call arg.__pos__()
  1518. pos_method = BuiltinVariable(getattr).call_function(
  1519. tx, [arg, ConstantVariable.create("__pos__")], {}
  1520. )
  1521. return pos_method.call_function(tx, [], {})
  1522. def call_index(self, tx: "InstructionTranslator", arg: "VariableTracker"):
  1523. if isinstance(arg, variables.TensorVariable):
  1524. unimplemented_v2(
  1525. gb_type="unsupported index(Tensor)",
  1526. context="",
  1527. explanation="Dynamo does not support tracing builtin index() on a Tensor",
  1528. hints=[],
  1529. )
  1530. arg = guard_if_dyn(arg)
  1531. constant_value = operator.index(arg)
  1532. return variables.ConstantVariable.create(constant_value)
  1533. def call_round(self, tx: "InstructionTranslator", arg, *args, **kwargs):
  1534. # Call arg.__round__()
  1535. round_method = BuiltinVariable(getattr).call_function(
  1536. tx, [arg, ConstantVariable.create("__round__")], {}
  1537. )
  1538. return round_method.call_function(tx, args, kwargs)
  1539. def call_range(self, tx: "InstructionTranslator", *args):
  1540. if check_unspec_or_constant_args(args, {}):
  1541. return variables.RangeVariable(args)
  1542. elif self._dynamic_args(*args):
  1543. args = tuple(
  1544. variables.ConstantVariable.create(guard_if_dyn(arg)) for arg in args
  1545. )
  1546. return variables.RangeVariable(args)
  1547. # None no-ops this handler and lets the driving function proceed
  1548. return None
  1549. def _dynamic_args(self, *args, **kwargs):
  1550. return any(isinstance(x, SymNodeVariable) for x in args) or any(
  1551. isinstance(x, SymNodeVariable) for x in kwargs.values()
  1552. )
  1553. def call_slice(self, tx: "InstructionTranslator", *args):
  1554. return variables.SliceVariable(args)
  1555. def _dyn_proxy(self, tx: "InstructionTranslator", *args, **kwargs):
  1556. from .builder import wrap_fx_proxy
  1557. return wrap_fx_proxy(
  1558. tx,
  1559. tx.output.create_proxy(
  1560. "call_function", self.fn, *proxy_args_kwargs(args, kwargs)
  1561. ),
  1562. )
  1563. # NOTE must handle IteratorVariable separately!
  1564. def _call_iter_tuple_list(
  1565. self, tx: "InstructionTranslator", obj=None, *args, **kwargs
  1566. ):
  1567. assert not isinstance(obj, variables.IteratorVariable)
  1568. if self._dynamic_args(*args, **kwargs):
  1569. return self._dyn_proxy(tx, *args, **kwargs)
  1570. cls = variables.BaseListVariable.cls_for(self.fn)
  1571. if obj is None:
  1572. return cls(
  1573. [],
  1574. mutation_type=ValueMutationNew(),
  1575. )
  1576. elif obj.has_unpack_var_sequence(tx):
  1577. if obj.source and not is_constant_source(obj.source):
  1578. if isinstance(obj, TupleIteratorVariable):
  1579. install_guard(
  1580. obj.source.make_guard(GuardBuilder.TUPLE_ITERATOR_LEN)
  1581. )
  1582. else:
  1583. if (
  1584. getattr(obj, "source", False)
  1585. and isinstance(obj, ConstDictVariable)
  1586. and not istype(obj, (SetVariable, FrozensetVariable))
  1587. ):
  1588. tx.output.guard_on_key_order.add(obj.source)
  1589. if isinstance(obj, variables.MappingProxyVariable):
  1590. # This could be an overguarding, but its rare to iterate
  1591. # through a mapping proxy and not use the keys.
  1592. install_guard(
  1593. obj.source.make_guard(GuardBuilder.MAPPING_KEYS_CHECK)
  1594. )
  1595. elif not isinstance(obj, variables.UnspecializedNNModuleVariable):
  1596. # Prevent calling __len__ method for guards, the tracing
  1597. # of __iter__ will insert the right guards later.
  1598. install_guard(
  1599. obj.source.make_guard(GuardBuilder.SEQUENCE_LENGTH)
  1600. )
  1601. return cls(
  1602. list(obj.unpack_var_sequence(tx)),
  1603. mutation_type=ValueMutationNew(),
  1604. )
  1605. def _call_iter_tuple_generator(self, tx, obj, *args, **kwargs):
  1606. cls = variables.BaseListVariable.cls_for(self.fn)
  1607. return cls(
  1608. list(obj.force_unpack_var_sequence(tx)), # exhaust generator
  1609. mutation_type=ValueMutationNew(),
  1610. )
  1611. def _call_tuple_list(self, tx, obj=None, *args, **kwargs):
  1612. if isinstance(obj, variables.IteratorVariable):
  1613. cls = variables.BaseListVariable.cls_for(self.fn)
  1614. return cls(
  1615. list(obj.force_unpack_var_sequence(tx)),
  1616. mutation_type=ValueMutationNew(),
  1617. )
  1618. elif isinstance(obj, variables.LocalGeneratorObjectVariable) or (
  1619. isinstance(obj, UserDefinedObjectVariable)
  1620. and obj.has_force_unpack_var_sequence(tx)
  1621. ):
  1622. return self._call_iter_tuple_generator(tx, obj, *args, **kwargs)
  1623. else:
  1624. return self._call_iter_tuple_list(tx, obj, *args, **kwargs)
  1625. def call_iter(self, tx: "InstructionTranslator", obj, *args, **kwargs):
  1626. if isinstance(obj, variables.IteratorVariable):
  1627. ret = obj
  1628. elif isinstance(obj, variables.RangeVariable):
  1629. ret = obj.call_method(tx, "__iter__", [], {})
  1630. else:
  1631. # Handle the case where we are iterating over a tuple, list or iterator
  1632. ret = self._call_iter_tuple_list(tx, obj, *args, **kwargs)
  1633. if ret is None:
  1634. # If the object doesn't implement a __iter__ method, it will be an error in eager mode when calling iter on it anyway.
  1635. # If the object implements a __iter__ method, inlining effectively forwards the call to another iter call
  1636. # (e.g. when __iter__ just returns iter(self.list)) or return a user-defined iterator.
  1637. # If the object implements a __getitem__ method, iter(...) will call obj.__getitem__()
  1638. # with an integer argument starting at 0, until __getitem__ raises IndexError
  1639. ret = variables.UserFunctionVariable(
  1640. polyfills.builtins.iter_
  1641. ).call_function(tx, [obj, *args], {})
  1642. if len(args):
  1643. # iter(obj, sentinel) returns an object that implements
  1644. # __iter__ and __next__ methods (UserDefinedObjectVariable)
  1645. # Wrap the return value in a IteratorVariable subclass (LazyObjectIteratorVariable)
  1646. # that forwards the next_variable call to the object.
  1647. ret = variables.ObjectIteratorVariable(ret)
  1648. return ret
  1649. call_tuple = _call_tuple_list
  1650. call_list = _call_tuple_list
  1651. def call_callable(self, tx: "InstructionTranslator", arg):
  1652. from .functions import BaseUserFunctionVariable, FunctoolsPartialVariable
  1653. from .nn_module import NNModuleVariable
  1654. if isinstance(
  1655. arg,
  1656. (
  1657. variables.UserDefinedClassVariable,
  1658. BaseUserFunctionVariable,
  1659. FunctoolsPartialVariable,
  1660. NNModuleVariable,
  1661. ),
  1662. ):
  1663. return variables.ConstantVariable.create(True)
  1664. elif isinstance(arg, UserDefinedVariable):
  1665. return variables.ConstantVariable.create(callable(arg.value))
  1666. elif isinstance(
  1667. arg,
  1668. (
  1669. ConstantVariable,
  1670. SymNodeVariable,
  1671. TensorVariable,
  1672. ListVariable,
  1673. TupleVariable,
  1674. ListIteratorVariable,
  1675. ),
  1676. ):
  1677. return variables.ConstantVariable.create(False)
  1678. def call_cast(self, _, *args, **kwargs):
  1679. if len(args) == 2:
  1680. return args[1]
  1681. unimplemented_v2(
  1682. gb_type="bad args to builtin cast()",
  1683. context=f"got args {args} {kwargs}",
  1684. explanation="Dynamo expects exactly 2 args to builtin cast().",
  1685. hints=["Ensure your call to cast() has exactly 2 arguments."],
  1686. )
  1687. def call_dir(self, tx: "InstructionTranslator", arg):
  1688. if isinstance(arg, variables.UserDefinedClassVariable):
  1689. return VariableTracker.build(tx, dir(arg.value))
  1690. if isinstance(arg, BuiltinVariable):
  1691. return VariableTracker.build(tx, dir(arg.fn))
  1692. def call_dict(self, tx: "InstructionTranslator", *args, **kwargs):
  1693. return BuiltinVariable.call_custom_dict(tx, dict, *args, **kwargs)
  1694. @staticmethod
  1695. def call_custom_dict(tx: "InstructionTranslator", user_cls, *args, **kwargs):
  1696. args = list(args)
  1697. if (
  1698. len(args) == 1
  1699. and isinstance(args[0], variables.GetAttrVariable)
  1700. and isinstance(args[0].obj, variables.UserDefinedClassVariable)
  1701. and not tx.output.side_effects.has_pending_mutation(args[0].obj)
  1702. ):
  1703. # Forward the GetAttrVariable(foo, "__dict__") to a realized vt of
  1704. # VT(foo.__dict__). This simplifies the construction of the new
  1705. # dict.
  1706. args[0] = args[0].get_forwarded_dict(tx)
  1707. return tx.inline_user_function_return(
  1708. VariableTracker.build(tx, polyfills.construct_dict),
  1709. [VariableTracker.build(tx, user_cls), *args],
  1710. kwargs,
  1711. )
  1712. @staticmethod
  1713. def call_custom_dict_fromkeys(
  1714. tx: "InstructionTranslator", user_cls, *args, **kwargs
  1715. ):
  1716. assert user_cls in {dict, OrderedDict, defaultdict}
  1717. if kwargs:
  1718. # Only `OrderedDict.fromkeys` accepts `value` passed by keyword
  1719. assert user_cls is OrderedDict
  1720. assert len(args) == 1 and len(kwargs) == 1 and "value" in kwargs
  1721. args = (*args, kwargs.pop("value"))
  1722. if len(args) == 0:
  1723. msg = ConstantVariable.create(
  1724. "fromkeys expected at least 1 arguments, got 0"
  1725. )
  1726. raise_observed_exception(TypeError, tx, args=[msg])
  1727. if len(args) == 1:
  1728. args = (*args, ConstantVariable.create(None))
  1729. assert len(args) == 2
  1730. arg, value = args
  1731. DictVariableType = (
  1732. ConstDictVariable if user_cls is not defaultdict else DefaultDictVariable
  1733. )
  1734. if isinstance(arg, dict):
  1735. arg = [ConstantVariable.create(k) for k in arg.keys()]
  1736. return DictVariableType(
  1737. dict.fromkeys(arg, value), user_cls, mutation_type=ValueMutationNew()
  1738. )
  1739. elif arg.has_force_unpack_var_sequence(tx):
  1740. keys = arg.force_unpack_var_sequence(tx)
  1741. if all(is_hashable(v) for v in keys):
  1742. return DictVariableType(
  1743. dict.fromkeys(keys, value),
  1744. user_cls,
  1745. mutation_type=ValueMutationNew(),
  1746. )
  1747. unimplemented_v2(
  1748. gb_type="failed to call dict.fromkeys()",
  1749. context=f"{user_cls.__name__}.fromkeys(): {args} {kwargs}",
  1750. explanation=f"Failed to call {user_cls.__name__}.fromkeys() because "
  1751. "arguments could not be automatically converted to a list, "
  1752. "or some dict key is not hashable.",
  1753. hints=[
  1754. "Manually convert the argument to a list.",
  1755. "Ensure all keys are hashable.",
  1756. ],
  1757. )
  1758. def call_set(self, tx: "InstructionTranslator", *args, **kwargs):
  1759. # Can we merge this implementation and call_dict's one?
  1760. assert not kwargs
  1761. if not args:
  1762. return SetVariable([], mutation_type=ValueMutationNew())
  1763. if len(args) != 1:
  1764. raise_observed_exception(
  1765. TypeError,
  1766. tx,
  1767. args=[
  1768. ConstantVariable.create(
  1769. f"set() takes 1 positional argument but {len(args)} were given"
  1770. )
  1771. ],
  1772. )
  1773. arg = args[0]
  1774. if istype(arg, variables.SetVariable):
  1775. return arg.clone(mutation_type=ValueMutationNew())
  1776. elif arg.has_force_unpack_var_sequence(tx):
  1777. items = arg.force_unpack_var_sequence(tx)
  1778. return SetVariable(items, mutation_type=ValueMutationNew())
  1779. elif isinstance(arg, variables.UserDefinedObjectVariable) and isinstance(
  1780. arg.value, KeysView
  1781. ):
  1782. iter_fn = arg.var_getattr(tx, "__iter__")
  1783. if isinstance(iter_fn, variables.UserMethodVariable):
  1784. out = tx.inline_user_function_return(iter_fn, args, kwargs)
  1785. if isinstance(out, SetVariable):
  1786. return out
  1787. return BuiltinVariable(set).call_set(tx, out)
  1788. raise_observed_exception(
  1789. TypeError,
  1790. tx,
  1791. args=[ConstantVariable.create("failed to construct builtin set()")],
  1792. )
  1793. def call_frozenset(self, tx: "InstructionTranslator", *args, **kwargs):
  1794. assert not kwargs
  1795. if not args:
  1796. return FrozensetVariable([])
  1797. if len(args) != 1:
  1798. raise_observed_exception(
  1799. TypeError,
  1800. tx,
  1801. args=[
  1802. ConstantVariable.create(
  1803. f"frozenset() takes 1 positional argument but {len(args)} were given"
  1804. )
  1805. ],
  1806. )
  1807. arg = args[0]
  1808. if istype(arg, variables.FrozensetVariable):
  1809. return FrozensetVariable([x.vt for x in arg.set_items])
  1810. elif arg.has_force_unpack_var_sequence(tx):
  1811. items = arg.force_unpack_var_sequence(tx)
  1812. return FrozensetVariable(items)
  1813. raise_observed_exception(
  1814. TypeError,
  1815. tx,
  1816. args=[ConstantVariable.create("failed to construct builtin frozenset()")],
  1817. )
  1818. def call_zip(self, tx: "InstructionTranslator", *args, **kwargs):
  1819. if kwargs:
  1820. assert len(kwargs) == 1 and "strict" in kwargs
  1821. strict = kwargs.pop("strict", False)
  1822. args = [BuiltinVariable(iter).call_function(tx, [arg], {}) for arg in args]
  1823. return variables.ZipVariable(
  1824. args, strict=strict, mutation_type=ValueMutationNew()
  1825. )
  1826. def call_len(self, tx: "InstructionTranslator", *args, **kwargs):
  1827. try:
  1828. return args[0].call_method(tx, "__len__", args[1:], kwargs)
  1829. except AttributeError as e:
  1830. raise_observed_exception(type(e), tx, args=list(e.args))
  1831. def call_getitem(self, tx: "InstructionTranslator", *args, **kwargs):
  1832. return args[0].call_method(tx, "__getitem__", args[1:], kwargs)
  1833. def call_isinstance(self, tx: "InstructionTranslator", arg, isinstance_type):
  1834. try:
  1835. arg_type = arg.python_type()
  1836. except NotImplementedError:
  1837. unimplemented_v2(
  1838. gb_type="builtin isinstance() cannot determine type of argument",
  1839. context=f"isinstance({arg}, {isinstance_type})",
  1840. explanation=f"Dynamo doesn't have a rule to determine the type of argument {arg}",
  1841. hints=[*graph_break_hints.DYNAMO_BUG],
  1842. )
  1843. isinstance_type = isinstance_type.as_python_constant()
  1844. if isinstance(arg, variables.TensorVariable) and arg.dtype is not None:
  1845. def _tensor_isinstance(tensor_var, tensor_type):
  1846. def check_type(ty):
  1847. if ty not in tensortype_to_dtype:
  1848. example_val = arg.as_proxy().node.meta["example_value"]
  1849. if (
  1850. is_traceable_wrapper_subclass(example_val)
  1851. and ty is torch.nn.parameter.Parameter
  1852. ):
  1853. # N.B: we are calling isinstance directly on the example value.
  1854. # torch.nn.Parameter has a meta-class that overrides __isinstance__,
  1855. # the isinstance check here allows us to invoke that logic.
  1856. return isinstance(example_val, ty)
  1857. else:
  1858. return issubclass(arg.python_type(), ty)
  1859. dtypes = tensortype_to_dtype[ty]
  1860. return arg.dtype in dtypes
  1861. if type(tensor_type) is tuple:
  1862. return any(check_type(ty) for ty in tensor_type)
  1863. else:
  1864. return check_type(tensor_type)
  1865. return variables.ConstantVariable.create(
  1866. _tensor_isinstance(arg, isinstance_type)
  1867. )
  1868. # UserDefinedObject with C extensions can have torch.Tensor attributes,
  1869. # so break graph.
  1870. if isinstance(arg, variables.UserDefinedObjectVariable) and isinstance(
  1871. arg.value, types.MemberDescriptorType
  1872. ):
  1873. unimplemented_v2(
  1874. gb_type="isinstance() called on user defined object with C extensions",
  1875. context=f"isinstance({arg}, {isinstance_type})",
  1876. explanation="User-defined object with C extensions can have torch.Tensor "
  1877. "attributes; intentionally graph breaking.",
  1878. hints=[*graph_break_hints.SUPPORTABLE],
  1879. )
  1880. # handle __instancecheck__ defined in user class
  1881. if (
  1882. isinstance(arg, variables.UserDefinedObjectVariable)
  1883. and "__instancecheck__" in isinstance_type.__class__.__dict__
  1884. ):
  1885. return variables.ConstantVariable.create(
  1886. isinstance_type.__class__.__instancecheck__(isinstance_type, arg.value)
  1887. )
  1888. if isinstance(arg, variables.UserDefinedExceptionClassVariable):
  1889. return ConstantVariable.create(isinstance(arg_type, isinstance_type))
  1890. isinstance_type_tuple: tuple[type, ...]
  1891. if isinstance(isinstance_type, type) or callable(
  1892. # E.g. isinstance(obj, typing.Sequence)
  1893. getattr(isinstance_type, "__instancecheck__", None)
  1894. ):
  1895. isinstance_type_tuple = (isinstance_type,)
  1896. elif sys.version_info >= (3, 10) and isinstance(
  1897. isinstance_type, types.UnionType
  1898. ):
  1899. isinstance_type_tuple = isinstance_type.__args__
  1900. elif isinstance(isinstance_type, tuple) and all(
  1901. isinstance(tp, type) or callable(getattr(tp, "__instancecheck__", None))
  1902. for tp in isinstance_type
  1903. ):
  1904. isinstance_type_tuple = isinstance_type
  1905. else:
  1906. raise_observed_exception(
  1907. TypeError,
  1908. tx,
  1909. args=[
  1910. "isinstance() arg 2 must be a type, a tuple of types, or a union"
  1911. ],
  1912. )
  1913. try:
  1914. # NB: `isinstance()` does not call `__subclasscheck__` but use `__instancecheck__`.
  1915. # But usually `isinstance(obj, type_info)` and `issubclass(type(obj), type_info)` gives
  1916. # the same result.
  1917. # WARNING: This might run arbitrary user code `__subclasscheck__` and we did not trace
  1918. # through it. This is a limitation of the current implementation.
  1919. # Usually `__subclasscheck__` and `__instancecheck__` can be constant fold through, it
  1920. # might not be a big issue and we trade off it for performance.
  1921. val = issubclass(arg_type, isinstance_type_tuple)
  1922. except TypeError:
  1923. val = arg_type in isinstance_type_tuple
  1924. return variables.ConstantVariable.create(val)
  1925. def call_issubclass(self, tx: "InstructionTranslator", left_ty, right_ty):
  1926. """Checks if first arg is subclass of right arg"""
  1927. try:
  1928. left_ty_py = left_ty.as_python_constant()
  1929. right_ty_py = right_ty.as_python_constant()
  1930. except NotImplementedError:
  1931. unimplemented_v2(
  1932. gb_type="issubclass() with non-constant arguments",
  1933. context=f"issubclass({left_ty}, {right_ty})",
  1934. explanation="issubclass() with non-constant arguments not supported.",
  1935. hints=[
  1936. "Make sure your arguments are types.",
  1937. *graph_break_hints.USER_ERROR,
  1938. ],
  1939. )
  1940. # WARNING: This might run arbitrary user code `__subclasscheck__`.
  1941. # See the comment in call_isinstance above.
  1942. return variables.ConstantVariable(issubclass(left_ty_py, right_ty_py))
  1943. def call_super(self, tx: "InstructionTranslator", a, b):
  1944. return variables.SuperVariable(a, b)
  1945. def call_next(self, tx: "InstructionTranslator", *args):
  1946. arg = args[0]
  1947. try:
  1948. return arg.next_variable(tx)
  1949. except ObservedUserStopIteration:
  1950. if len(args) == 2:
  1951. return args[1]
  1952. raise
  1953. except Unsupported as ex:
  1954. if isinstance(arg, variables.BaseListVariable):
  1955. ex.remove_from_stats()
  1956. return arg.items[0]
  1957. raise
  1958. def call_hasattr(self, tx: "InstructionTranslator", obj, attr):
  1959. if attr.is_python_constant():
  1960. name = attr.as_python_constant()
  1961. if isinstance(obj, variables.BuiltinVariable):
  1962. return variables.ConstantVariable(hasattr(obj.fn, name))
  1963. return obj.call_obj_hasattr(tx, name)
  1964. def call_map(self, tx: "InstructionTranslator", fn, *seqs):
  1965. seqs = [
  1966. seq.unpack_var_sequence(tx) if seq.has_unpack_var_sequence(tx) else seq
  1967. for seq in seqs
  1968. ]
  1969. return variables.MapVariable(fn, seqs, mutation_type=ValueMutationNew())
  1970. def call_filter(self, tx: "InstructionTranslator", fn, seq):
  1971. seq = seq.unpack_var_sequence(tx) if seq.has_unpack_var_sequence(tx) else seq
  1972. return variables.FilterVariable(fn, seq, mutation_type=ValueMutationNew())
  1973. def var_getattr(self, tx: "InstructionTranslator", name):
  1974. source = self.source and AttrSource(self.source, name)
  1975. if self.fn is object:
  1976. # for object, we can just directly read the attribute
  1977. try:
  1978. value = getattr(self.fn, name)
  1979. except AttributeError:
  1980. raise_observed_exception(AttributeError, tx)
  1981. if not callable(value):
  1982. return VariableTracker.build(tx, value, source)
  1983. return variables.GetAttrVariable(self, name, source=source)
  1984. def call_getattr(
  1985. self,
  1986. tx: "InstructionTranslator",
  1987. obj: VariableTracker,
  1988. name_var: VariableTracker,
  1989. default=None,
  1990. ):
  1991. if not name_var.is_python_constant():
  1992. unimplemented_v2(
  1993. gb_type="getattr() with non-constant name argument",
  1994. context=f"getattr({obj}, {name_var}, {default})",
  1995. explanation="getattr() with non-constant name argument is not supported",
  1996. hints=["Ensure the name argument of getattr() is a string"],
  1997. )
  1998. name = name_var.as_python_constant()
  1999. # See NOTE [Tensor "grad" and "_grad" attr]
  2000. if isinstance(obj, TensorVariable) and name == "_grad":
  2001. name = "grad"
  2002. if tx.output.side_effects.is_attribute_mutation(obj):
  2003. if isinstance(obj, variables.UnspecializedNNModuleVariable):
  2004. if (
  2005. name
  2006. in (
  2007. "named_parameters",
  2008. "parameters",
  2009. "named_buffers",
  2010. "buffers",
  2011. "named_modules",
  2012. "modules",
  2013. )
  2014. and obj.is_state_mutated
  2015. and tx.output.side_effects.has_pending_mutation(obj)
  2016. ):
  2017. unimplemented_v2(
  2018. gb_type="getattr() on nn.Module with pending mutation",
  2019. context=f"getattr({obj}, {name}, {default})",
  2020. explanation="Intentionally graph breaking on getattr() on a nn.Module "
  2021. "with a pending mutation",
  2022. hints=[],
  2023. )
  2024. if tx.output.side_effects.has_pending_mutation_of_attr(obj, name):
  2025. return tx.output.side_effects.load_attr(obj, name)
  2026. if default is not None:
  2027. hasattr_var = self.call_hasattr(tx, obj, name_var)
  2028. assert hasattr_var.as_python_constant() in (True, False)
  2029. if not hasattr_var.as_python_constant():
  2030. return default
  2031. source = obj.source and AttrSource(obj.source, name)
  2032. if name in {"__bases__", "__base__", "__flags__"}:
  2033. try:
  2034. value = obj.as_python_constant()
  2035. if isinstance(value, type):
  2036. if name == "__bases__":
  2037. tuple_args = [
  2038. VariableTracker.build(
  2039. tx, b, source and GetItemSource(source, i)
  2040. )
  2041. for i, b in enumerate(value.__bases__)
  2042. ]
  2043. return variables.TupleVariable(tuple_args, source=source)
  2044. if name == "__base__":
  2045. return VariableTracker.build(tx, value.__base__, source)
  2046. if name == "__flags__":
  2047. return ConstantVariable.create(value.__flags__)
  2048. except NotImplementedError:
  2049. pass
  2050. if isinstance(obj, variables.NNModuleVariable):
  2051. return obj.var_getattr(tx, name)
  2052. elif isinstance(
  2053. obj,
  2054. (
  2055. variables.TensorVariable,
  2056. variables.NamedTupleVariable,
  2057. variables.ConstantVariable,
  2058. variables.DistributedVariable,
  2059. variables.UserDefinedClassVariable,
  2060. variables.UserDefinedObjectVariable,
  2061. ),
  2062. ):
  2063. if (
  2064. isinstance(obj, variables.UserDefinedObjectVariable)
  2065. and issubclass(obj.value.__class__, unittest.TestCase)
  2066. and config.enable_trace_unittest
  2067. and name
  2068. in (
  2069. "assertRaisesRegex",
  2070. "assertNotWarns",
  2071. "assertWarnsRegex",
  2072. "assertWarns",
  2073. )
  2074. ):
  2075. unimplemented_v2(
  2076. gb_type="Failed to trace unittest method",
  2077. context=f"function: unittest.TestCase.{name}",
  2078. explanation=f"Dynamo does not know how to trace unittest method `{name}` ",
  2079. hints=[
  2080. f"Avoid calling `TestCase.{name}`. "
  2081. "Please report an issue to PyTorch.",
  2082. ],
  2083. )
  2084. if isinstance(obj, TensorVariable):
  2085. fake_val = obj.proxy.node.meta["example_value"]
  2086. if (
  2087. isinstance(fake_val, torch.Tensor)
  2088. and is_sparse_any(fake_val)
  2089. and (not tx.export or not config.capture_sparse_compute)
  2090. ):
  2091. unimplemented_v2(
  2092. gb_type="Attempted to wrap sparse Tensor",
  2093. context="",
  2094. explanation="torch.compile does not support sparse Tensors",
  2095. hints=[*graph_break_hints.SUPPORTABLE],
  2096. )
  2097. try:
  2098. return obj.var_getattr(tx, name)
  2099. except NotImplementedError:
  2100. return variables.GetAttrVariable(obj, name, source=source)
  2101. elif isinstance(obj, variables.TorchInGraphFunctionVariable):
  2102. # Get OpOverload from an OpOverloadPacket, e.g., torch.ops.aten.add.default.
  2103. member = getattr(obj.value, name)
  2104. if isinstance(
  2105. member, (torch._ops.OpOverloadPacket, torch._ops.OpOverload)
  2106. ) and torch._dynamo.trace_rules.is_aten_op_or_tensor_method(member):
  2107. return variables.TorchInGraphFunctionVariable(member, source=source)
  2108. elif name in cmp_name_to_op_mapping:
  2109. return variables.GetAttrVariable(obj, name, source=source)
  2110. elif isinstance(obj, DummyModule):
  2111. # TODO(mlazos) - Do we need this?
  2112. if obj.is_torch or name not in obj.value.__dict__:
  2113. member = getattr(obj.value, name)
  2114. else:
  2115. member = obj.value.__dict__[name]
  2116. if config.replay_record_enabled:
  2117. tx.exec_recorder.record_module_access(obj.value, name, member) # type: ignore[arg-type, union-attr]
  2118. return VariableTracker.build(tx, member, source)
  2119. elif istype(obj, variables.UserFunctionVariable) and name in (
  2120. "__name__",
  2121. "__module__",
  2122. ):
  2123. return ConstantVariable.create(getattr(obj.fn, name))
  2124. else:
  2125. try:
  2126. return obj.var_getattr(tx, name)
  2127. except NotImplementedError:
  2128. return variables.GetAttrVariable(obj, name, source=source)
  2129. def call_setattr(
  2130. self,
  2131. tx: "InstructionTranslator",
  2132. obj: VariableTracker,
  2133. name_var: VariableTracker,
  2134. val: VariableTracker,
  2135. ):
  2136. if isinstance(
  2137. obj,
  2138. (
  2139. variables.PlacementVariable,
  2140. variables.NamedTupleVariable,
  2141. variables.UserDefinedObjectVariable,
  2142. variables.NestedUserFunctionVariable,
  2143. variables.ExceptionVariable,
  2144. ),
  2145. ):
  2146. return obj.call_method(tx, "__setattr__", [name_var, val], {})
  2147. elif (
  2148. tx.output.side_effects.is_attribute_mutation(obj)
  2149. and name_var.is_python_constant()
  2150. ):
  2151. name = name_var.as_python_constant()
  2152. if isinstance(obj, variables.TensorVariable):
  2153. from .builder import wrap_fx_proxy
  2154. # Some special handling for tensor attributes.
  2155. if name == "requires_grad":
  2156. # TODO(voz): Make it work properly
  2157. unimplemented_v2(
  2158. gb_type="setattr() on Tensor.requires_grad",
  2159. context=f"setattr({obj}, {name}, {val})",
  2160. explanation="setattr() on Tensor.requires_grad not supported. "
  2161. "Mutating requires_grad can introduce a new leaf from non-leaf or vice versa in "
  2162. "the middle of the graph, which AOTAutograd does not currently know how to handle.",
  2163. hints=[*graph_break_hints.SUPPORTABLE],
  2164. )
  2165. elif name == "data":
  2166. # See comments on `test_set_data_on_scoped_tensor` for plans
  2167. # to support this.
  2168. if obj.source is None:
  2169. unimplemented_v2(
  2170. gb_type="Failed to mutate tensor data attribute",
  2171. context=f"setattr({obj}, {name}, {val})",
  2172. explanation="Dyanmo only supports mutating `.data`"
  2173. " of tensor created outside `torch.compile` region",
  2174. hints=[
  2175. "Don't mutate `.data` on this tensor, or move "
  2176. "the mutation out of `torch.compile` region",
  2177. ],
  2178. )
  2179. elif obj.dtype != val.dtype: # type: ignore[attr-defined]
  2180. unimplemented_v2(
  2181. gb_type="Failed to mutate tensor data attribute to different dtype",
  2182. context=f"setattr({obj}, {name}, {val})",
  2183. explanation="Dyanmo only supports mutating `.data`"
  2184. " of tensor to a new one with the same dtype",
  2185. hints=[
  2186. "Don't mutate `.data` on this tensor, or move "
  2187. "the mutation out of `torch.compile` region",
  2188. ],
  2189. )
  2190. # Remove the old reference in tracked fakes - if we don't do this
  2191. # new .data value size and shape differences will cause
  2192. # tracked fakes to produce incorrect guards. This is sound because the TensorVariable
  2193. # coming out of set_() below will be a new one, and get
  2194. # installed in tracked fakes.
  2195. to_remove = [
  2196. tf for tf in tx.output.tracked_fakes if tf.source == obj.source
  2197. ]
  2198. for tf in to_remove:
  2199. tx.output.tracked_fakes.remove(tf)
  2200. # Step 1 - disable grads
  2201. with dynamo_disable_grad(tx), torch.no_grad():
  2202. # Step 2 - call `set_`
  2203. out = wrap_fx_proxy(
  2204. tx,
  2205. tx.output.create_proxy(
  2206. "call_function",
  2207. torch.Tensor.set_,
  2208. *proxy_args_kwargs([obj, val], {}),
  2209. ),
  2210. )
  2211. # Step 3 - drop the version counter - this is a step required to get
  2212. # .data setting to play correctly with the autograd engine.
  2213. # Essentially, dynamo is trying to faithfully preserve the (absurd)
  2214. # behavior of .data= from eager mode
  2215. def _lower_version_count_by_1(x):
  2216. version = x._version
  2217. if version > 0:
  2218. version = version - 1
  2219. torch._C._autograd._unsafe_set_version_counter((x,), (version,))
  2220. return x
  2221. tx.output.create_proxy(
  2222. "call_function",
  2223. _lower_version_count_by_1,
  2224. (out.as_proxy(),),
  2225. {},
  2226. )
  2227. _lower_version_count_by_1(obj.as_proxy().node.meta["example_value"])
  2228. # This handles options prop, guards and ends with a clone
  2229. # Step 4 - replace all reference to the current object with the new one
  2230. return out
  2231. elif name in ("_grad", "grad"):
  2232. # NOTE: [Tensor "grad" and "_grad" attr]
  2233. # _grad and grad share the same setter/getter, see
  2234. # THPVariable_properties, and here we make sure setting one
  2235. # enables reading `val` from the other, by routing all
  2236. # read/write to `grad`.
  2237. name = "grad"
  2238. elif is_tensor_getset_descriptor(name):
  2239. # Attribute like `torch.Tensor.real` has special setters we
  2240. # don't yet support; it's not as simple adding an entry to
  2241. # the side effect mapping.
  2242. unimplemented_v2(
  2243. gb_type="Failed to set tensor attribute",
  2244. context=f"setattr({obj}, {name}, {val})",
  2245. explanation="Dyanmo doesn't support setting these tensor attributes",
  2246. hints=[
  2247. f"Don't mutate attribute '{name}' on tensors, or "
  2248. "move the mutation out of `torch.compile` region",
  2249. ],
  2250. )
  2251. tx.output.side_effects.store_attr(obj, name, val)
  2252. return val
  2253. elif isinstance(obj, variables.NNModuleVariable):
  2254. if not tx.output.is_root_tracer():
  2255. raise AttributeMutationError(
  2256. "Can't inplace modify module params/buffers inside HigherOrderOp"
  2257. )
  2258. if name_var.is_python_constant() and isinstance(
  2259. val, variables.TensorVariable
  2260. ):
  2261. assigning_fake_val = get_fake_value(val.as_proxy().node, tx)
  2262. try:
  2263. getattr_var = obj.var_getattr(tx, name_var.as_python_constant())
  2264. except (AttributeError, ObservedAttributeError):
  2265. getattr_var = None
  2266. if isinstance(getattr_var, variables.TensorVariable):
  2267. # get_fake_val will get the same fake tensor
  2268. existing_fake_attr = get_fake_value(getattr_var.as_proxy().node, tx)
  2269. # same tensor identity, setattr is a no-op
  2270. mod_setattr = inspect.getattr_static(obj.module_type, "__setattr__")
  2271. if (
  2272. existing_fake_attr is assigning_fake_val
  2273. and mod_setattr is torch.nn.Module.__setattr__
  2274. ):
  2275. return getattr_var
  2276. obj.convert_to_unspecialized(tx)
  2277. def call_delattr(
  2278. self,
  2279. tx: "InstructionTranslator",
  2280. obj: VariableTracker,
  2281. name_var: VariableTracker,
  2282. ):
  2283. return obj.call_method(tx, "__delattr__", [name_var], {})
  2284. def call_type(self, tx: "InstructionTranslator", obj: VariableTracker):
  2285. try:
  2286. py_type = obj.python_type()
  2287. except NotImplementedError as error:
  2288. raise UserError(
  2289. UserErrorType.INVALID_INPUT,
  2290. str(error),
  2291. case_name="unknown_python_type",
  2292. ) from None
  2293. source = obj.source and TypeSource(obj.source)
  2294. if (
  2295. source is None
  2296. and isinstance(obj, variables.UserDefinedObjectVariable)
  2297. and obj.cls_source
  2298. ):
  2299. source = obj.cls_source
  2300. if py_type is torch.Tensor:
  2301. # In some cases torch isn't available in globals
  2302. name = tx.output.install_global_by_id("", torch)
  2303. source = AttrSource(GlobalSource(name), "Tensor")
  2304. return VariableTracker.build(tx, py_type, source)
  2305. def call_reversed(self, tx: "InstructionTranslator", obj: VariableTracker):
  2306. if obj.has_unpack_var_sequence(tx):
  2307. items = list(reversed(obj.unpack_var_sequence(tx)))
  2308. return variables.TupleVariable(items)
  2309. def call_sorted(
  2310. self,
  2311. tx: "InstructionTranslator",
  2312. obj: VariableTracker,
  2313. **kwargs: VariableTracker,
  2314. ):
  2315. if obj.has_force_unpack_var_sequence(tx) and not isinstance(
  2316. obj, variables.TensorVariable
  2317. ):
  2318. list_var = variables.ListVariable(
  2319. obj.force_unpack_var_sequence(tx),
  2320. mutation_type=ValueMutationNew(),
  2321. )
  2322. list_var.call_method(tx, "sort", [], kwargs)
  2323. return list_var
  2324. # neg is a constant fold function, so we only get here if constant fold is not valid
  2325. def call_neg(self, tx: "InstructionTranslator", a):
  2326. if isinstance(a, SymNodeVariable):
  2327. return SymNodeVariable.create(
  2328. tx,
  2329. (operator.neg)(a.as_proxy()),
  2330. sym_num=None,
  2331. )
  2332. if (
  2333. isinstance(a, UserDefinedObjectVariable)
  2334. and a.call_obj_hasattr(tx, "__neg__").value # type: ignore[attr-defined]
  2335. ):
  2336. return a.call_method(tx, "__neg__", [], {})
  2337. # None no-ops this handler and lets the driving function proceed
  2338. return None
  2339. def call_format(self, tx: "InstructionTranslator", _format_string, *args, **kwargs):
  2340. format_string = _format_string.as_python_constant()
  2341. format_string = str(format_string)
  2342. return variables.StringFormatVariable.create(format_string, args, kwargs)
  2343. def call_id(self, tx: "InstructionTranslator", *args):
  2344. if len(args) > 0 and isinstance(args[0], variables.NNModuleVariable):
  2345. nn_mod_variable = args[0]
  2346. mod = tx.output.get_submodule(nn_mod_variable.module_key)
  2347. return variables.ConstantVariable.create(id(mod))
  2348. elif len(args) == 1 and isinstance(
  2349. args[0],
  2350. (variables.UserDefinedClassVariable, variables.UserDefinedObjectVariable),
  2351. ):
  2352. if args[0].source:
  2353. install_guard(args[0].source.make_guard(GuardBuilder.ID_MATCH))
  2354. constant_result = id(args[0].value)
  2355. return variables.ConstantVariable.create(constant_result)
  2356. elif len(args) == 1 and isinstance(args[0], TensorVariable):
  2357. tensor_variable = args[0]
  2358. return tensor_variable.call_id(tx)
  2359. elif istype(args[0], variables.UserFunctionVariable):
  2360. return variables.ConstantVariable.create(id(args[0].fn))
  2361. elif istype(args[0], variables.SkipFunctionVariable):
  2362. return variables.ConstantVariable.create(id(args[0].value))
  2363. elif istype(args[0], variables.FunctoolsPartialVariable):
  2364. return variables.ConstantVariable.create(id(args[0].fake_value))
  2365. else:
  2366. unimplemented_v2(
  2367. gb_type="id() with unsupported args",
  2368. context=str(args),
  2369. explanation=f"Dynamo doesn't know how to trace id() call with args {args}",
  2370. hints=[
  2371. "Supported args are Tensors, and functions/nn.Modules/user-defined objects "
  2372. "from outside the compiled region.",
  2373. *graph_break_hints.SUPPORTABLE,
  2374. ],
  2375. )
  2376. def call_deepcopy(self, tx: "InstructionTranslator", x):
  2377. unimplemented_v2(
  2378. gb_type="copy.deepcopy()",
  2379. context=f"copy.deepcopy({x})",
  2380. explanation="Dynamo does not support copy.deepcopy()",
  2381. hints=[
  2382. "Avoid calling copy.deepcopy()",
  2383. *graph_break_hints.SUPPORTABLE,
  2384. ],
  2385. )
  2386. def _comparison_with_tensor(self, tx: "InstructionTranslator", left, right):
  2387. from .builder import wrap_fx_proxy_cls
  2388. from .tensor import supported_tensor_comparison_op_values
  2389. op = self.fn
  2390. if op in [operator.is_, operator.is_not]:
  2391. is_result = (
  2392. isinstance(left, TensorVariable)
  2393. and isinstance(right, TensorVariable)
  2394. and id(extract_fake_example_value(left.as_proxy().node))
  2395. == id(extract_fake_example_value(right.as_proxy().node))
  2396. )
  2397. if op is operator.is_:
  2398. return ConstantVariable.create(is_result)
  2399. else:
  2400. return ConstantVariable.create(not is_result)
  2401. if op not in supported_tensor_comparison_op_values:
  2402. unimplemented_v2(
  2403. gb_type="unsupported Tensor comparison op",
  2404. context=f"{op.__name__}({left}, {right})",
  2405. explanation=f"Dynamo does not support the comparison op {op.__name__} "
  2406. f"with Tensor arguments {left}, {right}",
  2407. hints=[*graph_break_hints.SUPPORTABLE],
  2408. )
  2409. if (
  2410. isinstance(left, TensorVariable)
  2411. and isinstance(right, TensorVariable)
  2412. and (left.size and right.size) is not None
  2413. and left.size != right.size
  2414. ):
  2415. try:
  2416. torch.broadcast_shapes(left.size, right.size)
  2417. except RuntimeError:
  2418. # not broadcastable, can't be compared
  2419. unimplemented_v2(
  2420. gb_type="failed to broadcast when attempting Tensor comparison op",
  2421. context=f"{op.__name__}({left}, {right})",
  2422. explanation=f"Dynamo was unable to broad cast the arguments {left}, {right} "
  2423. f"when attempting to trace the comparison op {op.__name__}.",
  2424. hints=[*graph_break_hints.USER_ERROR],
  2425. )
  2426. tensor_cls = left if isinstance(left, TensorVariable) else right
  2427. proxy = tx.output.create_proxy(
  2428. "call_function", op, (left.as_proxy(), right.as_proxy()), {}
  2429. )
  2430. return wrap_fx_proxy_cls(
  2431. type(tensor_cls), # handle Ndarrays and Tensors
  2432. tx,
  2433. proxy,
  2434. )
  2435. def _comparison_with_symnode(self, tx: "InstructionTranslator", left, right):
  2436. from .tensor import supported_tensor_comparison_op_values
  2437. op = self.fn
  2438. if op not in supported_tensor_comparison_op_values:
  2439. unimplemented_v2(
  2440. gb_type="unsupported SymNode comparison op",
  2441. context=f"{op.__name__}({left}, {right})",
  2442. explanation=f"Dynamo does not support the comparison op {op.__name__} "
  2443. f"with SymNode arguments {left}, {right}",
  2444. hints=[*graph_break_hints.SUPPORTABLE],
  2445. )
  2446. # This is seen in inspect signature where we check if the value is a default value
  2447. if isinstance(right, variables.UserDefinedClassVariable):
  2448. return variables.ConstantVariable(op(object(), None))
  2449. proxy = tx.output.create_proxy(
  2450. "call_function", op, (left.as_proxy(), right.as_proxy()), {}
  2451. )
  2452. return SymNodeVariable.create(
  2453. tx,
  2454. proxy,
  2455. sym_num=None,
  2456. )
  2457. def call_xor(self, tx: "InstructionTranslator", a, b):
  2458. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2459. return a.call_method(tx, "__xor__", [b], {})
  2460. def call_ixor(self, tx: "InstructionTranslator", a, b):
  2461. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2462. return a.call_method(tx, "__ixor__", [b], {})
  2463. def call_sub(self, tx: "InstructionTranslator", a, b):
  2464. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2465. return a.call_method(tx, "__sub__", [b], {})
  2466. def call_isub(self, tx: "InstructionTranslator", a, b):
  2467. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2468. return a.call_method(tx, "__isub__", [b], {})
  2469. def call_and_(self, tx: "InstructionTranslator", a, b):
  2470. # Rely on constant_handler
  2471. if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
  2472. return None
  2473. if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
  2474. b, (SymNodeVariable, ConstantVariable)
  2475. ):
  2476. return SymNodeVariable.create(
  2477. tx,
  2478. tx.output.create_proxy(
  2479. "call_function", operator.and_, *proxy_args_kwargs([a, b], {})
  2480. ),
  2481. sym_num=None,
  2482. )
  2483. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2484. return a.call_method(tx, "__and__", [b], {})
  2485. # None no-ops this handler and lets the driving function proceed
  2486. def call_iand(self, tx: "InstructionTranslator", a, b):
  2487. # Rely on constant_handler
  2488. if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
  2489. return None
  2490. if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
  2491. b, (SymNodeVariable, ConstantVariable)
  2492. ):
  2493. return SymNodeVariable.create(
  2494. tx,
  2495. tx.output.create_proxy(
  2496. "call_function", operator.iand, *proxy_args_kwargs([a, b], {})
  2497. ),
  2498. sym_num=None,
  2499. )
  2500. if isinstance(a, (DictKeysVariable, SetVariable, UserDefinedObjectVariable)):
  2501. return a.call_method(tx, "__iand__", [b], {})
  2502. def call_or_(self, tx: "InstructionTranslator", a, b):
  2503. # Rely on constant_handler
  2504. if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
  2505. return None
  2506. if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
  2507. b, (SymNodeVariable, ConstantVariable)
  2508. ):
  2509. return SymNodeVariable.create(
  2510. tx,
  2511. tx.output.create_proxy(
  2512. "call_function", operator.or_, *proxy_args_kwargs([a, b], {})
  2513. ),
  2514. sym_num=None,
  2515. )
  2516. # This call looks like `{"one": torch.ones(1)} | {"two": torch.ones(2)}`.
  2517. if isinstance(
  2518. a,
  2519. (
  2520. ConstDictVariable,
  2521. DictKeysVariable,
  2522. MutableMappingVariable,
  2523. SetVariable,
  2524. UserDefinedDictVariable,
  2525. UserDefinedObjectVariable,
  2526. ),
  2527. ):
  2528. # TODO(guilhermeleobas): forward the call to b.__ror__(a) if
  2529. # a.__ror__(b) returns NotImplemented
  2530. return a.call_method(tx, "__or__", [b], {})
  2531. # None no-ops this handler and lets the driving function proceed
  2532. return None
  2533. def call_ior(self, tx: "InstructionTranslator", a, b):
  2534. # Rely on constant_handler
  2535. if isinstance(a, ConstantVariable) and isinstance(b, ConstantVariable):
  2536. return None
  2537. if isinstance(a, (SymNodeVariable, ConstantVariable)) and isinstance(
  2538. b, (SymNodeVariable, ConstantVariable)
  2539. ):
  2540. return SymNodeVariable.create(
  2541. tx,
  2542. tx.output.create_proxy(
  2543. "call_function", operator.ior, *proxy_args_kwargs([a, b], {})
  2544. ),
  2545. sym_num=None,
  2546. )
  2547. # This call looks like `{"one": torch.ones(1)} |= {"two": torch.ones(2)}`.
  2548. if isinstance(
  2549. a,
  2550. (
  2551. ConstDictVariable,
  2552. DictKeysVariable,
  2553. MutableMappingVariable,
  2554. SetVariable,
  2555. UserDefinedObjectVariable,
  2556. ),
  2557. ):
  2558. return a.call_method(tx, "__ior__", [b], {})
  2559. # None no-ops this handler and lets the driving function proceed
  2560. return None
  2561. def call_not_(self, tx: "InstructionTranslator", a):
  2562. if isinstance(a, SymNodeVariable):
  2563. return SymNodeVariable.create(
  2564. tx,
  2565. tx.output.create_proxy(
  2566. "call_function", operator.not_, *proxy_args_kwargs([a], {})
  2567. ),
  2568. sym_num=None,
  2569. )
  2570. # Unwrap the underlying ConstDictVariable
  2571. if isinstance(a, DictViewVariable):
  2572. a = a.dv_dict
  2573. if isinstance(a, (ListVariable, ConstDictVariable)):
  2574. return ConstantVariable.create(len(a.items) == 0)
  2575. return None
  2576. def call_contains(
  2577. self, tx: "InstructionTranslator", a: VariableTracker, b: VariableTracker
  2578. ):
  2579. return a.call_method(tx, "__contains__", [b], {})
  2580. @contextlib.contextmanager
  2581. def dynamo_disable_grad(tx):
  2582. from . import GradModeVariable
  2583. gmv = GradModeVariable.create(tx, False)
  2584. try:
  2585. gmv.enter(tx)
  2586. yield
  2587. finally:
  2588. gmv.exit(tx)