utils.py 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769
  1. # mypy: allow-untyped-defs
  2. import atexit
  3. import collections
  4. import contextlib
  5. import copy
  6. import dataclasses
  7. import datetime
  8. import dis
  9. import enum
  10. import functools
  11. import gc
  12. import inspect
  13. import itertools
  14. import linecache
  15. import logging
  16. import math
  17. import operator
  18. import os
  19. import re
  20. import sys
  21. import textwrap
  22. import threading
  23. import time
  24. import types
  25. import typing
  26. import warnings
  27. import weakref
  28. from contextlib import contextmanager
  29. from functools import lru_cache, wraps
  30. from types import MethodWrapperType
  31. from typing import (
  32. Any,
  33. Callable,
  34. cast,
  35. ClassVar,
  36. Counter,
  37. DefaultDict,
  38. Deque,
  39. Dict,
  40. Iterator,
  41. KeysView,
  42. List,
  43. Optional,
  44. Set,
  45. Tuple,
  46. Type,
  47. Union,
  48. ValuesView,
  49. )
  50. from ..utils.hooks import RemovableHandle
  51. try:
  52. import numpy as np
  53. except ModuleNotFoundError:
  54. np = None # type: ignore[assignment]
  55. try:
  56. import torch._logging
  57. import torch._numpy as tnp
  58. from torch._guards import detect_fake_mode # noqa: F401n
  59. from torch._logging import LazyString
  60. from . import config
  61. # NOTE: Make sure `NP_SUPPORTED_MODULES` and `NP_TO_TNP_MODULE` are in sync.
  62. if np:
  63. NP_SUPPORTED_MODULES: Tuple[types.ModuleType, ...] = (
  64. np,
  65. np.fft,
  66. np.linalg,
  67. np.random,
  68. )
  69. NP_TO_TNP_MODULE = {
  70. np: tnp,
  71. np.fft: tnp.fft,
  72. np.linalg: tnp.linalg,
  73. np.random: tnp.random,
  74. }
  75. else:
  76. NP_SUPPORTED_MODULES = tuple()
  77. NP_TO_TNP_MODULE = {}
  78. from torch._subclasses.fake_tensor import FakeTensor, is_fake, maybe_get_fake_mode
  79. except ImportError:
  80. pass
  81. import importlib
  82. import torch
  83. import torch._functorch.config
  84. import torch.fx.experimental.symbolic_shapes
  85. import torch.utils._pytree as pytree
  86. from torch import fx
  87. from torch._dispatch.python import enable_python_dispatcher
  88. from torch._guards import TracingContext
  89. from torch._subclasses.meta_utils import is_sparse_compressed
  90. from torch._utils_internal import log_compilation_event
  91. from torch.fx._utils import _format_graph_code, lazy_format_graph_code
  92. from torch.nn.modules.lazy import LazyModuleMixin
  93. from torch.utils._triton import has_triton, has_triton_package
  94. counters: DefaultDict[str, Counter[str]] = collections.defaultdict(collections.Counter)
  95. optimus_scuba_log: Dict[str, Any] = {}
  96. troubleshooting_url = (
  97. "https://pytorch.org/docs/main/torch.compiler_troubleshooting.html"
  98. )
  99. nnmodule_doc_url = "https://pytorch.org/docs/main/torch.compiler_nn_module.html"
  100. nnmodule_doc_url_msg = f"See {nnmodule_doc_url} for more information and limitations."
  101. log = logging.getLogger(__name__)
  102. # profiling compilation time by function
  103. compilation_time_metrics: Dict[str, List[float]] = {}
  104. # profiling compilation time by frame phase
  105. frame_phase_timing: Dict[str, Dict[str, float]] = collections.defaultdict(
  106. lambda: collections.defaultdict(float)
  107. )
  108. timer_counter = itertools.count()
  109. def tabulate(rows, headers):
  110. try:
  111. import tabulate
  112. return tabulate.tabulate(rows, headers=headers)
  113. except ImportError:
  114. return "\n".join(
  115. ", ".join(map(str, row)) for row in itertools.chain([headers], rows)
  116. )
  117. curr_frame = 0
  118. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  119. def increment_frame():
  120. global curr_frame
  121. curr_frame = curr_frame + 1
  122. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  123. def reset_frame_count():
  124. global curr_frame
  125. frame_phase_timing.clear()
  126. compilation_time_metrics.clear()
  127. curr_frame = 0
  128. op_count = 0
  129. def increment_op_count(cnt):
  130. global op_count
  131. op_count += cnt
  132. # Calculate total time spent so far for each phase
  133. # For example, {'entire_frame_compile':8.574629999999999, 'backend_compile':5.26806}
  134. def calculate_time_spent():
  135. total = 0.0
  136. total_by_key = {}
  137. for timings in frame_phase_timing.values():
  138. for key, timing in timings.items():
  139. total += timing
  140. if key not in total_by_key:
  141. total_by_key[key] = timing
  142. else:
  143. total_by_key[key] += timing
  144. return total_by_key
  145. # Print a report of time spent so far
  146. # Ex:
  147. # TIMING:
  148. # entire_frame_compile:8.574629999999999
  149. # backend_compile:5.26806
  150. def print_time_report():
  151. total_by_key = calculate_time_spent()
  152. out = "TIMING:"
  153. for key, value in total_by_key.items():
  154. out = f"{out} {key}:{round(value, 5)}"
  155. print(out)
  156. def _add_time_spent(key, phase_name, time_spent):
  157. frame_phase_timing[key][phase_name] += time_spent
  158. # dynamo_timed API works as a function decorator
  159. # By wrapping a function in dynamo_timed, we can store a record in compilation_time_metrics
  160. # where the key is the functions name.
  161. # For example:
  162. #
  163. # @dynamo_timed
  164. # def _foo(...):
  165. #
  166. # Would show up as an entry in our timing dict:
  167. # OrderedDict([('bar.<locals>._foo', [0.083690, 0.23949, 3.1425e-05])])
  168. # This is extremely useful for granular debugging.
  169. #
  170. # For a higher-level mode, pass a phase_name into dynamo_timed
  171. # phase_names record an extra record into a separate compilation timing structure,
  172. # one keyed on frame+name rather than function.
  173. # The frame is incremented outside of this function, in def increment_frame() above.
  174. # `fwd_only` is used to identify if this phase or function is only called
  175. # during compiling fwd graphs, e.g, `entire_frame_compile` and `backend_compile`.
  176. # The other phases (`inductor_compile` and `code_gen`) are called for both fwd and bwd graphs.
  177. def dynamo_timed(original_function=None, phase_name=None, fwd_only=True):
  178. def dynamo_timed_inner(func):
  179. @wraps(func)
  180. def time_wrapper(*args, **kwargs):
  181. key = func.__qualname__
  182. if key not in compilation_time_metrics:
  183. compilation_time_metrics[key] = []
  184. fail_type: Optional[str] = None
  185. fail_reason: Optional[str] = None
  186. time_spent = float("-inf")
  187. try:
  188. with torch.profiler.record_function(f"{key} (dynamo_timed)"):
  189. t0 = time.time()
  190. r = func(*args, **kwargs)
  191. time_spent = time.time() - t0
  192. compilation_time_metrics[key].append(time_spent)
  193. except Exception as e:
  194. fail_type = str(type(e))
  195. fail_reason = str(e)
  196. raise
  197. finally:
  198. # Only record backward compilation metrics if phase_name is not None!
  199. if phase_name:
  200. frame_key = str(curr_frame)
  201. # fwd only compilation stages: entire_frame_compile, backend_compile.
  202. # use frame_key as time aggregation key.
  203. if fwd_only and fail_type is None:
  204. _add_time_spent(frame_key, phase_name, time_spent)
  205. else:
  206. # fwd + bwd compilation stages: inductor_compile, code_gen.
  207. # use frame_key as time aggregation key for fwd graphs;
  208. # use compile_id as time aggregation key for bwd graphs.
  209. if torch._guards.TracingContext.try_get() is not None:
  210. aot_graph_name = str(
  211. torch._guards.TracingContext.get().aot_graph_name
  212. )
  213. if (
  214. "forward" in aot_graph_name
  215. or "inference" in aot_graph_name
  216. ) and fail_type is None:
  217. _add_time_spent(frame_key, phase_name, time_spent)
  218. elif "backward" in aot_graph_name:
  219. compile_id = str(
  220. torch._guards.CompileContext.current_compile_id()
  221. )
  222. if fail_type is None:
  223. _add_time_spent(compile_id, phase_name, time_spent)
  224. # log backward compilation metrics at the end of `inductor_compile` of bwd graph,
  225. # one record for one bwd graph.
  226. if phase_name == "inductor_compile":
  227. if fail_type is None:
  228. inductor_compile_time = frame_phase_timing[
  229. compile_id
  230. ].get("inductor_compile", None)
  231. code_gen_time = frame_phase_timing[
  232. compile_id
  233. ].get("code_gen", None)
  234. else:
  235. inductor_compile_time = None
  236. code_gen_time = None
  237. metrics = BwdCompilationMetrics(
  238. compile_id,
  239. inductor_compile_time,
  240. code_gen_time,
  241. fail_type,
  242. fail_reason,
  243. )
  244. record_compilation_metrics(metrics)
  245. return r
  246. return time_wrapper
  247. if original_function:
  248. return dynamo_timed_inner(original_function)
  249. return dynamo_timed_inner
  250. def compile_times(repr="str", aggregate=False):
  251. """
  252. Get metrics about torchdynamo frontend/backend compilation times.
  253. Accumulates information from functions tagged with `@dynamo_timed`.
  254. repr='str' returns a printable string for user interaction, and 'csv'
  255. returns headers, rows which can be logged for output
  256. aggregate causes values from multiple compilations (e.g. split graphs)
  257. to be accumulated into one value. If false, expect more than one value
  258. per metric.
  259. """
  260. def fmt_fn(values, item_fn=lambda x: x):
  261. if aggregate:
  262. return item_fn(sum(values))
  263. return ", ".join(map(item_fn, values))
  264. if repr == "str":
  265. rows = [
  266. (k, fmt_fn(compilation_time_metrics[k], item_fn=lambda x: f"{x:.4f}"))
  267. for k in compilation_time_metrics
  268. ]
  269. out = "TorchDynamo compilation metrics:\n"
  270. out += tabulate(rows, headers=("Function", "Runtimes (s)"))
  271. return out
  272. elif repr == "csv":
  273. values = [
  274. fmt_fn(v, item_fn=lambda x: f"{x:.6f}")
  275. for v in compilation_time_metrics.values()
  276. ]
  277. headers = list(compilation_time_metrics.keys())
  278. return headers, values
  279. @atexit.register
  280. def dump_compile_times():
  281. log.info(compile_times(repr="str", aggregate=True))
  282. tensortype_to_dtype = {
  283. torch.FloatTensor: (torch.float32, torch.float),
  284. torch.DoubleTensor: (torch.float64, torch.double),
  285. torch.HalfTensor: (torch.float16, torch.half),
  286. torch.BFloat16Tensor: (torch.bfloat16,),
  287. torch.ByteTensor: (torch.uint8,),
  288. torch.CharTensor: (torch.int8,),
  289. torch.LongTensor: (torch.int64, torch.long),
  290. torch.IntTensor: (torch.int32, torch.int),
  291. torch.ShortTensor: (torch.int16, torch.short),
  292. torch.BoolTensor: (torch.bool,),
  293. }
  294. class DuplicateWarningChecker:
  295. def __init__(self, maxsize=4096):
  296. self.maxsize = maxsize
  297. self.reset()
  298. def reset(self):
  299. self.set = collections.OrderedDict()
  300. def add(self, key):
  301. if key in self.set:
  302. self.set.move_to_end(key, last=True)
  303. if not config.verbose:
  304. return False
  305. else:
  306. self.set[key] = None
  307. while len(self.set) > self.maxsize:
  308. self.set.popitem(last=False)
  309. return True
  310. graph_break_dup_warning_checker = DuplicateWarningChecker()
  311. def setup_compile_debug():
  312. compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
  313. if compile_debug:
  314. return add_file_handler()
  315. return contextlib.ExitStack()
  316. def reset_graph_break_dup_checker():
  317. graph_break_dup_warning_checker.reset()
  318. def add_file_handler():
  319. log_path = os.path.join(get_debug_dir(), "torchdynamo")
  320. os.makedirs(log_path, exist_ok=True)
  321. log_file_handler = logging.FileHandler(os.path.join(log_path, "debug.log"))
  322. logger = logging.getLogger("torch._dynamo")
  323. logger.addHandler(log_file_handler)
  324. exitstack = contextlib.ExitStack()
  325. exitstack.callback(lambda: logger.removeHandler(log_file_handler))
  326. return exitstack
  327. def setup_log_file():
  328. exitstack = contextlib.ExitStack()
  329. if config.log_file_name is not None:
  330. log_file_handler = logging.FileHandler(config.log_file_name)
  331. for logger in torch._logging._internal.get_loggers():
  332. logger.addHandler(log_file_handler)
  333. exitstack.callback(lambda: logger.removeHandler(log_file_handler))
  334. return exitstack
  335. return exitstack
  336. def gen_record_file_name(exc, code):
  337. return f"{get_debug_dir()}/error_recordings/\
  338. {code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec"
  339. def write_record_to_file(filename, exec_record):
  340. try:
  341. if os.path.exists(filename):
  342. log.warning(
  343. "Unable to write execution record %s; file already exists.", filename
  344. )
  345. else:
  346. os.makedirs(os.path.dirname(filename), exist_ok=True)
  347. with open(filename, "wb") as f:
  348. exec_record.dump(f)
  349. except Exception:
  350. log.exception("Unable to write execution record %s", filename)
  351. def count_calls(g: fx.Graph):
  352. c = 0
  353. for n in g.nodes:
  354. if "call" in n.op:
  355. c += 1
  356. return c
  357. def identity(x):
  358. return x
  359. def hashable(x):
  360. try:
  361. hash(x)
  362. return True
  363. except TypeError:
  364. return False
  365. # cannot hash writable memoryview object
  366. except ValueError:
  367. return False
  368. def nothing(*args, **kwargs):
  369. pass
  370. class ExactWeakKeyDictionary:
  371. """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality"""
  372. def __init__(self):
  373. self.values = dict()
  374. self.refs = dict()
  375. def __getitem__(self, key):
  376. return self.values[id(key)]
  377. def get(self, key, default=None):
  378. return self.values.get(id(key), default)
  379. def __contains__(self, key):
  380. return id(key) in self.values
  381. def __setitem__(self, key, value):
  382. idx = id(key)
  383. if idx not in self.refs:
  384. self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx))
  385. self.values[idx] = value
  386. def _remove_id(self, idx):
  387. if idx in self.values:
  388. del self.values[idx]
  389. if idx in self.refs:
  390. del self.refs[idx]
  391. def clear(self):
  392. self.refs.clear()
  393. self.values.clear()
  394. def istype(obj, allowed_types):
  395. """isinstance() without subclasses"""
  396. if isinstance(allowed_types, (tuple, list, set)):
  397. return type(obj) in allowed_types
  398. return type(obj) is allowed_types
  399. if sys.version_info >= (3, 12):
  400. # Some typing classes moved to C in 3.12,
  401. # which no longer have the _Final mixin.
  402. _builtin_final_typing_classes = (
  403. typing.ParamSpecArgs,
  404. typing.ParamSpecKwargs,
  405. typing.ParamSpec,
  406. typing.TypeVar,
  407. typing.TypeVarTuple,
  408. typing.TypeAliasType,
  409. )
  410. def is_typing(value):
  411. # _Final catches most of typing classes:
  412. # - Any
  413. # - Callable
  414. # - Union
  415. # ...
  416. #
  417. # NB: we intentionally ignore classes that inherit from Generic, since they
  418. # can be used as both TypingVariable as well as UserDefinedClassVariable.
  419. if sys.version_info >= (3, 12) and isinstance(value, _builtin_final_typing_classes):
  420. return True
  421. return isinstance(value, typing._Final) or value is typing.Generic # type: ignore[attr-defined]
  422. def is_numpy_int_type(value):
  423. if not np:
  424. return False
  425. return istype(
  426. value,
  427. (
  428. np.int8,
  429. np.int16,
  430. np.int32,
  431. np.int64,
  432. np.uint8,
  433. np.uint16,
  434. np.uint32,
  435. np.uint64,
  436. ),
  437. )
  438. def is_numpy_float_type(value):
  439. if not np:
  440. return False
  441. return istype(
  442. value,
  443. (
  444. np.float16,
  445. np.float32,
  446. np.float64,
  447. ),
  448. )
  449. def is_function_or_wrapper(value):
  450. return (
  451. is_function(value)
  452. or isinstance(value, functools._lru_cache_wrapper)
  453. and is_function(inspect.getattr_static(value, "__wrapped__"))
  454. or isinstance(value, (torch._ops.OpOverloadPacket, torch._ops.OpOverload))
  455. )
  456. def is_function(value):
  457. return isinstance(
  458. value,
  459. (
  460. types.FunctionType,
  461. types.BuiltinFunctionType,
  462. types.MethodDescriptorType,
  463. types.WrapperDescriptorType,
  464. torch.jit.ScriptFunction,
  465. ),
  466. )
  467. def unwrap_if_wrapper(fn):
  468. return unwrap_with_attr_name_if_wrapper(fn)[0]
  469. def unwrap_with_attr_name_if_wrapper(fn):
  470. # unpack @functools.lru_cache wrapped function
  471. if isinstance(fn, functools._lru_cache_wrapper):
  472. fn = inspect.getattr_static(fn, "__wrapped__")
  473. attr_name = "__wrapped__"
  474. # unpack @torch._dynamo.optimize()(fn) wrapped function
  475. elif is_function(fn) and inspect.getattr_static(fn, "_torchdynamo_inline", False):
  476. fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn)
  477. attr_name = "_torchdynamo_inline"
  478. # unpack torch.jit.script_if_tracing
  479. elif is_function(fn) and inspect.getattr_static(
  480. fn, "__script_if_tracing_wrapper", False
  481. ):
  482. fn = inspect.getattr_static(fn, "__original_fn", fn)
  483. attr_name = "__original_fn"
  484. else:
  485. attr_name = None
  486. return fn, attr_name
  487. def is_numpy_ndarray(value):
  488. if not np:
  489. return False
  490. return istype(value, np.ndarray)
  491. def istensor(obj):
  492. """Check of obj is a tensor"""
  493. tensor_list = (
  494. torch.Tensor,
  495. torch.nn.Parameter,
  496. *config.traceable_tensor_subclasses,
  497. )
  498. tensor_list = tensor_list + (torch._subclasses.FakeTensor,)
  499. return istype(obj, tensor_list)
  500. def is_lazy_module(mod):
  501. return isinstance(mod, LazyModuleMixin)
  502. @functools.lru_cache(4096)
  503. def print_once(*args):
  504. print(*args)
  505. def make_cell(val=None):
  506. """Some black magic to create a cell object that usually only exists in a closure"""
  507. x = val
  508. def f():
  509. return x
  510. assert f.__closure__ is not None and len(f.__closure__) == 1
  511. return f.__closure__[0]
  512. def proxy_args_kwargs(args, kwargs):
  513. try:
  514. proxy_args = tuple(arg.as_proxy() for arg in args)
  515. proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()}
  516. return proxy_args, proxy_kwargs
  517. except NotImplementedError as e:
  518. from .exc import unimplemented
  519. from .variables.base import typestr
  520. unimplemented(
  521. f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}",
  522. from_exc=e,
  523. )
  524. @dataclasses.dataclass
  525. class CompilationMetrics:
  526. compile_id: str
  527. frame_key: str
  528. co_name: str
  529. co_filename: str
  530. co_firstlineno: int
  531. cache_size: int
  532. accumulated_cache_size: int
  533. guard_count: Optional[int]
  534. shape_env_guard_count: Optional[int]
  535. graph_op_count: Optional[int]
  536. graph_node_count: Optional[int]
  537. graph_input_count: Optional[int]
  538. start_time: float
  539. entire_frame_compile_time_s: Optional[float]
  540. backend_compile_time_s: Optional[float]
  541. inductor_compile_time_s: Optional[float]
  542. code_gen_time_s: Optional[float]
  543. fail_type: Optional[str]
  544. fail_reason: Optional[str]
  545. fail_user_frame_filename: Optional[str]
  546. fail_user_frame_lineno: Optional[int]
  547. non_compliant_ops: Set[str]
  548. compliant_custom_ops: Set[str]
  549. restart_reasons: Set[str]
  550. dynamo_time_before_restart_s: float
  551. # Sometimes, we will finish analyzing a frame but conclude we don't want
  552. # to install any guarded code. True means we actually decided to install
  553. # a compiled frame
  554. has_guarded_code: bool
  555. @dataclasses.dataclass
  556. class BwdCompilationMetrics:
  557. compile_id: str
  558. inductor_compile_time_s: Optional[float]
  559. code_gen_time_s: Optional[float]
  560. fail_type: Optional[str]
  561. fail_reason: Optional[str]
  562. DEFAULT_COMPILATION_METRICS_LIMIT = 64
  563. _compilation_metrics: Deque[
  564. Union[CompilationMetrics, BwdCompilationMetrics]
  565. ] = collections.deque(maxlen=DEFAULT_COMPILATION_METRICS_LIMIT)
  566. def record_compilation_metrics(
  567. compilation_metrics: Union[CompilationMetrics, BwdCompilationMetrics]
  568. ):
  569. global _compilation_metrics
  570. _compilation_metrics.append(compilation_metrics)
  571. if isinstance(compilation_metrics, CompilationMetrics):
  572. name = "compilation_metrics"
  573. else:
  574. name = "bwd_compilation_metrics"
  575. # Currently only record fwd compilation metrics, will add bwd compilation metrics
  576. # after the internal Scuba logging changes finish.
  577. if isinstance(compilation_metrics, CompilationMetrics):
  578. torch._logging.trace_structured(
  579. name,
  580. lambda: {
  581. k: list(v) if isinstance(v, set) else v
  582. for k, v in dataclasses.asdict(compilation_metrics).items()
  583. },
  584. )
  585. if config.log_compilation_metrics:
  586. log_compilation_event(compilation_metrics)
  587. def set_compilation_metrics_limit(new_size: int) -> None:
  588. global _compilation_metrics
  589. while len(_compilation_metrics) > new_size:
  590. _compilation_metrics.popleft()
  591. new_deque = collections.deque(_compilation_metrics, maxlen=new_size)
  592. _compilation_metrics = new_deque
  593. def clear_compilation_metrics() -> None:
  594. global _compilation_metrics
  595. _compilation_metrics.clear()
  596. def get_compilation_metrics() -> List[Union[CompilationMetrics, BwdCompilationMetrics]]:
  597. return list(_compilation_metrics)
  598. @dataclasses.dataclass
  599. class CleanupHook:
  600. """Remove a global variable when hook is called"""
  601. scope: Dict[str, Any]
  602. name: str
  603. def __call__(self, *args):
  604. # Make sure we're not shutting down
  605. if CleanupManager is not None:
  606. CleanupManager.count -= 1
  607. del self.scope[self.name]
  608. @staticmethod
  609. def create(scope, name, val):
  610. assert name not in scope
  611. CleanupManager.count += 1
  612. scope[name] = val
  613. return CleanupHook(scope, name)
  614. class CleanupManager(ExactWeakKeyDictionary):
  615. count = 0
  616. instance: ClassVar["CleanupManager"]
  617. def _remove_id(self, idx):
  618. for hook in self.values[idx]:
  619. hook()
  620. super()._remove_id(idx)
  621. CleanupManager.instance = CleanupManager()
  622. def clone_tensor(x):
  623. """Clone the tensor and its gradient"""
  624. y = x.clone().requires_grad_(x.requires_grad)
  625. if x.is_leaf and x.grad is not None:
  626. y.grad = x.grad.clone()
  627. return y
  628. def clone_input(x, *, dtype=None):
  629. """copy while preserving strides"""
  630. # TODO: this is questionable
  631. if is_fake(x):
  632. # this func fails on fake tensors in __torch_dispatch__
  633. return x
  634. def torch_clone(x):
  635. y = torch.clone(x)
  636. if x.is_leaf:
  637. y.requires_grad_(x.requires_grad)
  638. if x.is_leaf and x.grad is not None:
  639. y.grad = clone_input(x.grad, dtype=dtype)
  640. if hasattr(x, "_dynamo_dynamic_indices"):
  641. y._dynamo_dynamic_indices = x._dynamo_dynamic_indices.copy() # type: ignore[attr-defined]
  642. return y
  643. with torch.no_grad():
  644. if x.device.type == "xla":
  645. # Access data_ptr() for a xla tensor will cause crash
  646. return torch_clone(x)
  647. # Handle sparse storage (no stride).
  648. if x.layout is torch.sparse_coo:
  649. return torch.sparse_coo_tensor(
  650. torch_clone(x._indices()),
  651. torch_clone(x._values()),
  652. x.shape,
  653. is_coalesced=x.is_coalesced(),
  654. )
  655. elif is_sparse_compressed(x):
  656. if x.layout in {torch.sparse_csr, torch.sparse_bsr}:
  657. compressed_indices = x.crow_indices()
  658. plain_indices = x.col_indices()
  659. else:
  660. compressed_indices = x.ccol_indices()
  661. plain_indices = x.row_indices()
  662. return torch.sparse_compressed_tensor(
  663. torch_clone(compressed_indices),
  664. torch_clone(plain_indices),
  665. torch_clone(x.values()),
  666. x.shape,
  667. layout=x.layout,
  668. )
  669. needed_size = sum(
  670. (shape - 1) * stride for shape, stride in zip(x.size(), x.stride())
  671. )
  672. if x.is_quantized:
  673. result = torch.empty_quantized((needed_size + 32,), x)
  674. else:
  675. result = torch.empty(
  676. needed_size + 32, dtype=dtype or x.dtype, device=x.device
  677. )
  678. cache_line_offset = (
  679. (x.data_ptr() - result.data_ptr()) % 32
  680. ) // x.element_size()
  681. result.as_strided_(x.size(), x.stride(), cache_line_offset)
  682. try:
  683. result.copy_(x.clone())
  684. if x.is_leaf:
  685. result.requires_grad_(x.requires_grad)
  686. if x.is_leaf and x.grad is not None:
  687. result.grad = clone_input(x.grad, dtype=dtype)
  688. except RuntimeError:
  689. # RuntimeError: unsupported operation: more than one element of the written-to
  690. # tensor refers to a single memory location. Please clone() the tensor before
  691. # performing the operation.
  692. return torch_clone(x)
  693. if hasattr(x, "_dynamo_dynamic_indices"):
  694. result._dynamo_dynamic_indices = x._dynamo_dynamic_indices.copy() # type: ignore[attr-defined]
  695. return result
  696. def clone_inputs(example_inputs):
  697. res: Union[Dict[Any, Any], List[Any]]
  698. if type(example_inputs) is dict:
  699. res = dict(example_inputs)
  700. for key, value in res.items():
  701. if isinstance(value, tuple):
  702. res[key] = clone_inputs(value)
  703. else:
  704. assert isinstance(value, torch.Tensor), type(value)
  705. res[key] = clone_input(value)
  706. return res
  707. res = list(example_inputs)
  708. for i in range(len(res)):
  709. if isinstance(res[i], torch.Tensor):
  710. res[i] = clone_input(res[i])
  711. return res
  712. def skip_frame_if_in_functorch_mode(val: torch.Tensor):
  713. try:
  714. val.data_ptr() # will throw for functorch tensors
  715. except RuntimeError as e:
  716. from .exc import SkipFrame
  717. # This will be GradTrackingTensor/BatchedTensor/etc
  718. functorch_subclass_name = re.sub(r"\(.*", "", repr(val))
  719. raise SkipFrame(
  720. f"torch.compile cannot be run in context: {functorch_subclass_name}"
  721. ) from e
  722. @contextmanager
  723. def preserve_rng_state():
  724. disable_functorch = torch._C._DisableFuncTorch
  725. disable_current_modes = torch.utils._python_dispatch._disable_current_modes
  726. with disable_current_modes(), disable_functorch():
  727. rng_state = torch.clone(torch.random.get_rng_state())
  728. skip_frame_if_in_functorch_mode(rng_state)
  729. if torch.cuda.is_available():
  730. cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
  731. try:
  732. yield
  733. finally:
  734. with torch.utils._python_dispatch._disable_current_modes():
  735. torch.random.set_rng_state(rng_state)
  736. if torch.cuda.is_available():
  737. torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined]
  738. def is_jit_model(model0):
  739. return isinstance(
  740. model0,
  741. (
  742. torch.jit._trace.TopLevelTracedModule,
  743. torch.jit._script.RecursiveScriptModule,
  744. torch.jit.ScriptFunction,
  745. torch.jit.ScriptModule,
  746. ),
  747. )
  748. def torchscript(model, example_inputs, verbose=False):
  749. if is_jit_model(model):
  750. # already done?
  751. return model
  752. try:
  753. return torch.jit.trace(model, example_inputs)
  754. except Exception:
  755. try:
  756. return torch.jit.script(model)
  757. except Exception:
  758. if verbose:
  759. log.exception("jit error")
  760. else:
  761. log.error("Both torch.jit.trace and torch.jit.script failed")
  762. return None
  763. def getfile(obj):
  764. try:
  765. return inspect.getfile(obj)
  766. except (TypeError, OSError):
  767. return None
  768. def is_namedtuple(obj):
  769. """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
  770. return is_namedtuple_cls(type(obj))
  771. def is_namedtuple_cls(cls):
  772. """Test if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuple"""
  773. try:
  774. if issubclass(cls, tuple):
  775. bases = getattr(cls, "__bases__", []) or [None]
  776. module = getattr(cls, "__module__", None)
  777. return module in ("torch.return_types", "torch.autograd.forward_ad") or (
  778. bases[0] is tuple and hasattr(cls, "_make") and hasattr(cls, "_fields")
  779. )
  780. except TypeError:
  781. pass
  782. return False
  783. @functools.lru_cache(1)
  784. def namedtuple_fields(cls):
  785. """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple"""
  786. if cls is slice:
  787. return ["start", "stop", "step"]
  788. assert issubclass(cls, tuple)
  789. if hasattr(cls, "_fields"):
  790. # normal namedtuples
  791. return cls._fields
  792. @dataclasses.dataclass
  793. class Marker:
  794. index: int
  795. # frustrating ones e.g. torch.return_types.max
  796. assert cls.__module__ == "torch.return_types"
  797. obj = cls(map(Marker, range(cls.n_fields)))
  798. fields: List[Optional[str]] = [None] * cls.n_fields
  799. for name in dir(obj):
  800. if name[0] != "_" and isinstance(getattr(obj, name), Marker):
  801. fields[getattr(obj, name).index] = name
  802. return fields
  803. def checkpoint_params(gm):
  804. with torch.no_grad():
  805. rng_state = torch.clone(torch.random.get_rng_state())
  806. if torch.cuda.is_available():
  807. cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
  808. saved_state = []
  809. for param in itertools.chain(gm.parameters(), gm.buffers()):
  810. saved_state.append((param, param._version, torch.clone(param)))
  811. def restore():
  812. with torch.no_grad():
  813. torch.random.set_rng_state(rng_state)
  814. if torch.cuda.is_available():
  815. torch.cuda.set_rng_state(cuda_rng_state)
  816. for param, version, original_value in saved_state:
  817. if param._version != version:
  818. param.copy_(original_value)
  819. return restore
  820. def timed(model, example_inputs, times=1):
  821. if torch.cuda.is_available():
  822. synchronize = torch.cuda.synchronize
  823. else:
  824. synchronize = nothing
  825. synchronize()
  826. gc.collect()
  827. torch.manual_seed(1337)
  828. t0 = time.perf_counter()
  829. for _ in range(times):
  830. result = model(*example_inputs)
  831. synchronize()
  832. t1 = time.perf_counter()
  833. return result, t1 - t0 # type: ignore[possibly-undefined]
  834. def check_is_cuda(gm, example_inputs):
  835. return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True)))
  836. @lru_cache(32)
  837. def rot_n_helper(n):
  838. assert n > 1
  839. vars = [f"v{i}" for i in range(n)]
  840. rotated = reversed(vars[-1:] + vars[:-1])
  841. fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})")
  842. fn.__name__ = f"rot_{n}_helper"
  843. return fn
  844. common_constant_types = {
  845. int,
  846. float,
  847. complex,
  848. bool,
  849. str,
  850. bytes,
  851. type(None),
  852. Ellipsis.__class__,
  853. types.CodeType,
  854. torch.device,
  855. torch.dtype,
  856. torch.memory_format,
  857. torch.layout,
  858. }
  859. if has_triton_package():
  860. import triton
  861. common_constant_types.add(triton.language.dtype)
  862. def is_safe_constant(v):
  863. if istype(v, (tuple, frozenset)):
  864. return all(map(is_safe_constant, v))
  865. return isinstance(v, (enum.Enum, type)) or istype(
  866. v,
  867. common_constant_types | {slice},
  868. )
  869. def specialize_symnode(arg):
  870. from .variables import ConstantVariable, SymNodeVariable
  871. # Guard and specialize
  872. if isinstance(arg, SymNodeVariable):
  873. return ConstantVariable.create(arg.evaluate_expr())
  874. return arg
  875. def guard_if_dyn(arg):
  876. from .variables import ConstantVariable
  877. arg = specialize_symnode(arg)
  878. if isinstance(arg, ConstantVariable):
  879. return arg.as_python_constant()
  880. return arg
  881. def check_constant_args(args, kwargs):
  882. return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values()))
  883. def check_unspec_python_args(args, kwargs):
  884. from .variables.constant import ConstantVariable
  885. from .variables.tensor import UnspecializedPythonVariable
  886. unspec_count = 0
  887. for x in itertools.chain(args, kwargs.values()):
  888. if isinstance(x, UnspecializedPythonVariable):
  889. unspec_count += 1
  890. elif not isinstance(x, ConstantVariable):
  891. return False
  892. return unspec_count > 0
  893. def check_unspec_or_constant_args(args, kwargs):
  894. # A fused version of:
  895. # return check_constant_args(args, kwargs) or check_unspec_python_args(args, kwargs)
  896. from .variables.tensor import UnspecializedPythonVariable
  897. for x in itertools.chain(args, kwargs.values()):
  898. if not (x.is_python_constant() or isinstance(x, UnspecializedPythonVariable)):
  899. return False
  900. return True
  901. def check_numpy_ndarray_args(args, kwargs):
  902. from .variables.tensor import NumpyNdarrayVariable
  903. return any(
  904. isinstance(x, NumpyNdarrayVariable)
  905. for x in itertools.chain(args, kwargs.values())
  906. )
  907. dict_keys: Type[KeysView[Any]] = type(dict().keys())
  908. dict_values: Type[ValuesView[Any]] = type(dict().values())
  909. odict_values: Type[ValuesView[Any]] = type(collections.OrderedDict().values())
  910. tuple_iterator: Type[Iterator[Any]] = type(iter(tuple()))
  911. tuple_iterator_len = tuple_iterator.__length_hint__ # type: ignore[attr-defined]
  912. object_new = object.__new__
  913. def nn_module_new(cls):
  914. obj = object_new(cls)
  915. torch.nn.Module.__init__(obj)
  916. return obj
  917. def product(it):
  918. return functools.reduce(operator.mul, it, 1)
  919. def tuple_iterator_getitem(it, index):
  920. _, (obj,), start = it.__reduce__()
  921. return obj[start + index]
  922. iter_next = next
  923. def to_subclass(t, cls):
  924. return t.as_subclass(cls)
  925. def dict_keys_getitem(d, n):
  926. return next(itertools.islice(iter(d), n, n + 1))
  927. def enum_repr(value, local):
  928. # enum class can override __str__ method. Use __class__ and name attribute
  929. # to extract the class name and key name.
  930. name = value.__class__.__name__
  931. val = value.name
  932. scope = "L" if local else "G"
  933. local_name = f'{scope}["{name}"].{val}'
  934. return local_name
  935. def set_example_value(node, example_value):
  936. # NB: example_value is a bit of a misnomer, because this is always a fake
  937. # tensor of some sort. Furthermore, these example values serve as the
  938. # runtime state of Dynamo tracing, which means if metadata mutation
  939. # occurs, the example_value gets directly updated (so you can't rely on
  940. # this to accurately reflect what the state of the value was at the time
  941. # the program was traced).
  942. node.meta["example_value"] = example_value
  943. shape_env = TracingContext.get().fake_mode.shape_env
  944. if symbol_to_path := torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings(
  945. shape_env, example_value
  946. ):
  947. node.meta["unbacked_bindings"] = symbol_to_path
  948. def _get_fake_tensor(vt):
  949. fake_tensor = vt.as_proxy().node.meta.get("example_value")
  950. if not is_fake(fake_tensor):
  951. from .exc import unimplemented
  952. unimplemented("Cannot check Tensor object identity without its fake value")
  953. return fake_tensor
  954. def iter_contains(items, search, tx, check_tensor_identity=False):
  955. from .variables import (
  956. BuiltinVariable,
  957. ConstantVariable,
  958. TensorVariable,
  959. VariableTracker,
  960. )
  961. if search.is_python_constant():
  962. found_const = any(
  963. x.is_python_constant()
  964. and x.as_python_constant() == search.as_python_constant()
  965. for x in items
  966. )
  967. return ConstantVariable.create(found_const)
  968. must_check_tensor_id = False
  969. if check_tensor_identity and isinstance(search, TensorVariable):
  970. must_check_tensor_id = True
  971. # Match of Tensor means match of FakeTensor
  972. search = _get_fake_tensor(search)
  973. found: Optional[VariableTracker] = None
  974. for x in items:
  975. if must_check_tensor_id:
  976. if isinstance(x, TensorVariable):
  977. if search is _get_fake_tensor(x): # Object equivalence
  978. return ConstantVariable.create(True)
  979. else:
  980. check = BuiltinVariable(operator.eq).call_function(tx, [x, search], {})
  981. if found is None:
  982. found = check
  983. else:
  984. found = BuiltinVariable(operator.or_).call_function(
  985. tx, [check, found], {}
  986. )
  987. if found is None:
  988. found = ConstantVariable.create(False)
  989. return found
  990. def key_is_id(k):
  991. """Returns whether it indexes dictionaries using its id"""
  992. return isinstance(k, (torch.Tensor, torch.nn.Module, MethodWrapperType))
  993. def key_to_id(value):
  994. return [id(k) if key_is_id(k) else k for k in value.keys()]
  995. def const_repr(x, *, local) -> str:
  996. from .trace_rules import is_builtin_callable
  997. if isinstance(x, (list, tuple)):
  998. elems_repr = ",".join(const_repr(s, local=local) for s in x)
  999. if isinstance(x, list):
  1000. return f"[{elems_repr}]"
  1001. else:
  1002. assert isinstance(x, tuple)
  1003. if len(x) == 1:
  1004. return f"({elems_repr},)"
  1005. else:
  1006. return f"({elems_repr})"
  1007. elif isinstance(x, enum.Enum):
  1008. # To workaround repr(Enum) returning invalid global reference before python 3.11
  1009. # by calling enum_repr and removing quotes to render enum in guard code.
  1010. return enum_repr(x, local=local).replace("'", "")
  1011. elif is_builtin_callable(x):
  1012. return x.__name__
  1013. elif isinstance(x, type):
  1014. def fullname(o):
  1015. klass = o.__class__
  1016. module = klass.__module__
  1017. if module == "builtins":
  1018. return klass.__qualname__ # avoid outputs like 'builtins.str'
  1019. return module + "." + klass.__qualname__
  1020. return fullname(x)
  1021. else:
  1022. return f"{x!r}"
  1023. def dict_keys_repr(const_keys, *, local) -> str:
  1024. keys_str = ",".join(const_repr(s, local=local) for s in const_keys)
  1025. return "[" + keys_str + "]"
  1026. GLOBAL_KEY_PREFIX = "__dict_key"
  1027. from torch._subclasses import UnsupportedFakeTensorException # noqa: F401
  1028. def wrap_fake_exception(fn):
  1029. try:
  1030. return fn()
  1031. except UnsupportedFakeTensorException as e:
  1032. from .exc import unimplemented
  1033. msg = f"Unsupported: {e.reason} with fake tensor propagation."
  1034. log.warning(msg)
  1035. unimplemented(msg, from_exc=e)
  1036. def deepcopy_to_fake_tensor(obj, fake_mode):
  1037. with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode):
  1038. return wrap_fake_exception(lambda: copy.deepcopy(obj))
  1039. def rmse(ref, res):
  1040. """
  1041. Calculate root mean squared error
  1042. """
  1043. return torch.sqrt(torch.mean(torch.square(ref - res)))
  1044. def same(
  1045. ref,
  1046. res,
  1047. fp64_ref=None,
  1048. cos_similarity=False,
  1049. tol=1e-4,
  1050. equal_nan=False,
  1051. exact_dtype=True,
  1052. relax_numpy_equality=False,
  1053. ignore_non_fp=False,
  1054. log_error=log.error,
  1055. ):
  1056. """Check correctness to see if ref and res match"""
  1057. if fp64_ref is None:
  1058. fp64_ref = ref
  1059. if isinstance(ref, (list, tuple, torch.nn.ParameterList, torch.Size)):
  1060. assert isinstance(res, (list, tuple)), f"type mismatch {type(ref)} {type(res)}"
  1061. if len(ref) != len(res):
  1062. log_error("Length mismatch")
  1063. return False
  1064. return len(ref) == len(res) and all(
  1065. same(
  1066. ai,
  1067. bi,
  1068. fp64_refi,
  1069. cos_similarity,
  1070. tol,
  1071. equal_nan,
  1072. exact_dtype,
  1073. relax_numpy_equality,
  1074. ignore_non_fp,
  1075. log_error=log_error,
  1076. )
  1077. for ai, bi, fp64_refi in zip(ref, res, fp64_ref)
  1078. )
  1079. elif type(ref).__name__ == "QuestionAnsweringModelOutput":
  1080. # This skips checking accuracy for start_logits/end_logits.
  1081. # Tentatively, start_logits/end_logits appear to be very prone to
  1082. # inaccuracies and is somewhat subsumed by checking the loss.
  1083. return same(
  1084. ref.loss,
  1085. res.loss,
  1086. fp64_ref.loss,
  1087. cos_similarity,
  1088. tol,
  1089. equal_nan,
  1090. exact_dtype,
  1091. relax_numpy_equality,
  1092. ignore_non_fp,
  1093. log_error=log_error,
  1094. )
  1095. elif isinstance(ref, dict):
  1096. assert isinstance(res, dict)
  1097. assert set(ref.keys()) == set(
  1098. res.keys()
  1099. ), f"keys mismatch {set(ref.keys())} == {set(res.keys())}"
  1100. for k in sorted(ref.keys()):
  1101. if not (
  1102. same(
  1103. ref[k],
  1104. res[k],
  1105. fp64_ref[k],
  1106. cos_similarity=cos_similarity,
  1107. tol=tol,
  1108. equal_nan=equal_nan,
  1109. exact_dtype=exact_dtype,
  1110. relax_numpy_equality=relax_numpy_equality,
  1111. ignore_non_fp=ignore_non_fp,
  1112. log_error=log_error,
  1113. )
  1114. ):
  1115. log_error("Accuracy failed for key name %s", k)
  1116. return False
  1117. return True
  1118. elif isinstance(ref, (torch.Tensor, float)):
  1119. assert not isinstance(ref, torch._subclasses.FakeTensor)
  1120. assert not isinstance(res, torch._subclasses.FakeTensor)
  1121. def to_tensor(t):
  1122. return t if isinstance(t, torch.Tensor) else torch.tensor(t)
  1123. ref, res, fp64_ref = (to_tensor(val) for val in (ref, res, fp64_ref))
  1124. if ref.is_sparse:
  1125. assert res.is_sparse
  1126. ref = ref.to_dense()
  1127. res = res.to_dense()
  1128. assert isinstance(res, torch.Tensor), f"type mismatch {type(ref)} {type(res)}"
  1129. if exact_dtype:
  1130. if ref.dtype != res.dtype:
  1131. log_error("dtype mismatch %s, %s", ref.dtype, res.dtype)
  1132. return False
  1133. if ref.dtype == torch.bool:
  1134. if ignore_non_fp:
  1135. return True
  1136. # triton stores bool as int8, so add this for more accurate checking
  1137. r = torch.allclose(
  1138. ref.to(dtype=torch.uint8),
  1139. res.to(dtype=torch.uint8),
  1140. atol=tol,
  1141. rtol=tol,
  1142. equal_nan=equal_nan,
  1143. )
  1144. if not r:
  1145. log_error("Accuracy failed: uint8 tensor did not match")
  1146. return r
  1147. if cos_similarity:
  1148. ref = ref.flatten().to(torch.float32)
  1149. res = res.flatten().to(torch.float32)
  1150. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True):
  1151. # early exit that handles zero/nan better
  1152. # cosine_similarity(zeros(10), zeros(10), dim=0) is 0
  1153. return True
  1154. score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6)
  1155. if score < 0.99:
  1156. log.warning("Similarity score=%s", score.cpu().detach().item())
  1157. return score >= 0.99
  1158. else:
  1159. if not exact_dtype:
  1160. ref = ref.to(res.dtype)
  1161. # First try usual allclose
  1162. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan):
  1163. return True
  1164. # Check error from fp64 version
  1165. if fp64_ref.dtype == torch.float64:
  1166. ref_error = rmse(fp64_ref, ref).item()
  1167. # ref unable to produce this with stable numerics in this precision, ignore
  1168. if math.isnan(ref_error):
  1169. log.warning(
  1170. "Found nan in reference. Consider running in higher precision."
  1171. )
  1172. res_error = rmse(fp64_ref, res).item()
  1173. # In the case of using AMP (Automatic Mixed Precision), certain models have
  1174. # failed the benchmark's correctness check. However, the end-to-end model's
  1175. # accuracy when comparing AMP with FP32 is within a difference of less than 0.1%.
  1176. # Thus, it's possible that the correctness check failures for these models are
  1177. # false alarms. We use multiplier of 3 instead of 2 to avoid these false alarms.
  1178. multiplier = 3.0 if res.dtype == torch.bfloat16 else 2.0
  1179. if (
  1180. fp64_ref.numel() < 1000
  1181. or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1)
  1182. # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE
  1183. or tol >= 2 * 1e-2
  1184. ):
  1185. # In the presence of noise, noise might dominate our error
  1186. # metric for smaller tensors.
  1187. # Similary, for 1x1 kernels, there seems to be high noise with amp.
  1188. multiplier = 3.0
  1189. passes_test = res_error <= (multiplier * ref_error + tol / 10.0)
  1190. if not passes_test:
  1191. log_error(
  1192. "RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %f",
  1193. res_error,
  1194. ref_error,
  1195. res.size(),
  1196. res.dtype,
  1197. multiplier,
  1198. tol,
  1199. )
  1200. # import pdb; pdb.set_trace()
  1201. return passes_test
  1202. if ignore_non_fp:
  1203. return True
  1204. log_error("Accuracy failed: allclose not within tol=%s", tol)
  1205. return False
  1206. elif isinstance(ref, (str, int, type(None), bool, torch.device)):
  1207. if ignore_non_fp:
  1208. return True
  1209. r = ref == res
  1210. if not r:
  1211. log_error("Accuracy failed (%s): %s != %s", type(ref), ref, res)
  1212. return r
  1213. elif is_numpy_int_type(ref) or is_numpy_float_type(ref):
  1214. if relax_numpy_equality and not (
  1215. is_numpy_int_type(res) or is_numpy_float_type(res)
  1216. ):
  1217. ref = ref.item()
  1218. r = (type(ref) is type(res)) and (ref == res)
  1219. if not r:
  1220. log_error("Accuracy failed (numpy): %s != %s", ref, res)
  1221. return r
  1222. elif is_numpy_ndarray(ref):
  1223. return (type(ref) is type(res)) and same(
  1224. torch.as_tensor(ref),
  1225. torch.as_tensor(res),
  1226. fp64_ref,
  1227. cos_similarity=cos_similarity,
  1228. tol=tol,
  1229. equal_nan=equal_nan,
  1230. exact_dtype=exact_dtype,
  1231. relax_numpy_equality=relax_numpy_equality,
  1232. ignore_non_fp=ignore_non_fp,
  1233. log_error=log_error,
  1234. )
  1235. elif type(ref).__name__ in (
  1236. "MaskedLMOutput",
  1237. "Seq2SeqLMOutput",
  1238. "CausalLMOutputWithCrossAttentions",
  1239. "LongformerMaskedLMOutput",
  1240. "Instances",
  1241. "SquashedNormal",
  1242. "Boxes",
  1243. "Normal",
  1244. "TanhTransform",
  1245. "Foo",
  1246. "Variable",
  1247. ):
  1248. assert type(ref) is type(res)
  1249. return all(
  1250. same(
  1251. getattr(ref, key),
  1252. getattr(res, key),
  1253. getattr(fp64_ref, key),
  1254. cos_similarity=cos_similarity,
  1255. tol=tol,
  1256. equal_nan=equal_nan,
  1257. exact_dtype=exact_dtype,
  1258. relax_numpy_equality=relax_numpy_equality,
  1259. ignore_non_fp=ignore_non_fp,
  1260. log_error=log_error,
  1261. )
  1262. for key in ref.__dict__.keys()
  1263. )
  1264. else:
  1265. raise RuntimeError(f"unsupported type: {type(ref).__name__}")
  1266. def format_func_info(code):
  1267. short_filename = code.co_filename.split("/")[-1]
  1268. return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})"
  1269. @contextlib.contextmanager
  1270. def disable_cache_limit():
  1271. prior = config.cache_size_limit
  1272. config.cache_size_limit = sys.maxsize
  1273. prior_acc_limit = config.accumulated_cache_size_limit
  1274. config.accumulated_cache_size_limit = sys.maxsize
  1275. try:
  1276. yield
  1277. finally:
  1278. config.cache_size_limit = prior
  1279. config.accumulated_cache_size_limit = prior_acc_limit
  1280. # map from transformed code back to original user code
  1281. orig_code_map = ExactWeakKeyDictionary()
  1282. # keep a record of code_obj -> list of guard failure reasons for logging
  1283. guard_failures: DefaultDict[Any, List[Any]] = collections.defaultdict(list)
  1284. # Keep a record of graph break reasons for logging
  1285. graph_break_reasons: List["torch._dynamo.output_graph.GraphCompileReason"] = list()
  1286. # keep record of compiled code, if we are in "error if recompile"
  1287. # to track code that dynamo has compiled previously
  1288. seen_code_map = ExactWeakKeyDictionary()
  1289. class CompileProfiler:
  1290. """Utility for profiling how and what dynamo would compile.
  1291. Can be used for
  1292. * diagnosing recompilation issues
  1293. * determining an appropriate compile cache limit
  1294. * (TODO)confirming which functions got compiled/skipped
  1295. """
  1296. def __init__(self):
  1297. self.frame_count = 0
  1298. self.op_count = 0
  1299. self.backend_ctx_ctor = disable_cache_limit
  1300. def __call__(self, gm: torch.fx.GraphModule, example_inputs):
  1301. self.frame_count += 1
  1302. for node in gm.graph.nodes:
  1303. if "call" in node.op:
  1304. self.op_count += 1
  1305. return gm.forward
  1306. # no-op __enter__ and __exit__ to preserve BC
  1307. def __enter__(self):
  1308. return self
  1309. def __exit__(self, typ, val, traceback):
  1310. pass
  1311. def get_metrics(self):
  1312. return {"guard_failures": guard_failures}
  1313. def report(self):
  1314. metrics = self.get_metrics()
  1315. gf = metrics["guard_failures"]
  1316. def num_recompiles(code):
  1317. return len(gf[code])
  1318. def recompile_reasons(code):
  1319. return "\n".join([str(x) for x in gf[code]])
  1320. summarized_gf = [
  1321. [format_func_info(code), num_recompiles(code), recompile_reasons(code)]
  1322. for code in gf
  1323. ]
  1324. def graph_break_report():
  1325. if "graph_break" in counters:
  1326. graph_breaks = counters["graph_break"]
  1327. return tabulate(
  1328. [[msg, graph_breaks[msg]] for msg in graph_breaks],
  1329. headers=["Graph Break Reason", "Count"],
  1330. )
  1331. def recompilation_report():
  1332. if len(gf):
  1333. max_recompiles = max(num_recompiles(code) for code in gf)
  1334. recomp_table = tabulate(
  1335. summarized_gf,
  1336. headers=["Function", "Recompiles", "Recompile Reasons"],
  1337. )
  1338. return recomp_table + textwrap.dedent(
  1339. f"""
  1340. Set torch._dynamo.config.cache_size_limit to {max_recompiles} to avoid being cache limited.
  1341. """
  1342. )
  1343. report = textwrap.dedent(
  1344. """
  1345. Torchdynamo Profiler Report
  1346. ===========================
  1347. Graph Breaks
  1348. ------------
  1349. Graph breaks happen when torchdynamo encounters code it can't safely trace.
  1350. If you want to find out why breaks are happening, check below for each break reason
  1351. You may gain additional insight by passing `fullgraph=True` to torch.compile,
  1352. to stop at the first break.
  1353. """
  1354. )
  1355. report += graph_break_report() or "No graph breaks detected."
  1356. report += textwrap.dedent(
  1357. """
  1358. Recompilation
  1359. -------------
  1360. These subgraphs were recompiled more than once due to guard failures
  1361. Guard failures indicate some condition assumed to be static by the tracer changed,
  1362. making it unsafe to reuse the compiled program.
  1363. """
  1364. )
  1365. report += recompilation_report() or "No recompilation detected.\n"
  1366. return report
  1367. # return same dir unless user changes config between calls
  1368. @functools.lru_cache(None)
  1369. def _get_debug_dir(root_dir):
  1370. dir_name = (
  1371. "run_"
  1372. + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
  1373. # use pid to avoid conflicts among ranks
  1374. + "-pid_"
  1375. + str(os.getpid())
  1376. )
  1377. return os.path.join(root_dir, dir_name)
  1378. def get_debug_dir():
  1379. debug_root = config.debug_dir_root
  1380. return _get_debug_dir(debug_root)
  1381. def extract_fake_example_value(node, required=True):
  1382. if "example_value" in node.meta and is_fake(node.meta["example_value"]):
  1383. return node.meta["example_value"]
  1384. elif required:
  1385. from torch._dynamo.exc import unimplemented
  1386. unimplemented("`FakeTensor` example value was required but not available")
  1387. else:
  1388. return None
  1389. def ensure_graph_fake(e, tx):
  1390. assert maybe_get_fake_mode(e) is tx.fake_mode
  1391. return e
  1392. def get_fake_values_from_nodes(tx, nodes, allow_non_graph_fake):
  1393. def visit(n: torch.fx.Node):
  1394. if n.op == "call_function" and "example_value" not in n.meta:
  1395. # fake tensor validity is checked inside get_fake_value using
  1396. # ensure_graph_fake
  1397. return get_fake_value(n, tx, allow_non_graph_fake)
  1398. out = n.meta["example_value"]
  1399. if not allow_non_graph_fake and isinstance(out, torch.Tensor):
  1400. return ensure_graph_fake(out, tx)
  1401. return out
  1402. return torch.fx.node.map_arg(nodes, visit)
  1403. def get_fake_value(node, tx, allow_non_graph_fake=False):
  1404. """
  1405. Run the computation represented by `node` using fake tensors and return the result.
  1406. allow_non_graph_fake: whether to allow the return result to be:
  1407. 1. non-fake or 2. fake that is not created by this instance of Dynamo.
  1408. If `True`, you must be prepared to deal with such return values, ideally
  1409. by further wrapping them as this graph's fakes.
  1410. """
  1411. from torch.utils._sympy.value_ranges import ValueRangeError
  1412. from .exc import (
  1413. TorchRuntimeError,
  1414. unimplemented,
  1415. Unsupported,
  1416. UserError,
  1417. UserErrorType,
  1418. )
  1419. op = node.op
  1420. # FX Node should always return the same fake value
  1421. if "example_value" in node.meta and is_fake(node.meta["example_value"]):
  1422. return node.meta["example_value"]
  1423. args, kwargs = get_fake_values_from_nodes(
  1424. tx, (node.args, node.kwargs), allow_non_graph_fake
  1425. )
  1426. nnmodule = None
  1427. if op == "call_method" and len(args) > 0 and isinstance(args[0], torch.nn.Module):
  1428. # If the first argument is nn.Module, should copy to fake mode.
  1429. args = (deepcopy_to_fake_tensor(args[0], tx.fake_mode),) + tuple(args[1:])
  1430. if op == "call_module":
  1431. nnmodule = tx.output.nn_modules[node.target]
  1432. if is_lazy_module(nnmodule) and hasattr(nnmodule, "_initialize_hook"):
  1433. # In the case of a lazy module, we want to run
  1434. # the pre-hooks which initialize it.
  1435. # Afterwards, lazy module deletes its pre-hooks
  1436. # to avoid treating it as lazy on subsequent recompile.
  1437. nnmodule._infer_parameters(nnmodule, args)
  1438. # no matter it's lazy module or not, we should copy to fake mode.
  1439. nnmodule = deepcopy_to_fake_tensor(nnmodule, tx.fake_mode)
  1440. try:
  1441. with tx.fake_mode, enable_python_dispatcher():
  1442. ret_val = wrap_fake_exception(
  1443. lambda: run_node(tx.output, node, args, kwargs, nnmodule)
  1444. )
  1445. except Unsupported:
  1446. raise
  1447. except RuntimeError as e:
  1448. cause: BaseException = e
  1449. if e.__cause__ is not None:
  1450. cause = e.__cause__
  1451. if isinstance(
  1452. cause, torch._subclasses.fake_tensor.DataDependentOutputException
  1453. ):
  1454. unimplemented(
  1455. f"data dependent operator: {cause.func}; "
  1456. "to enable, set torch._dynamo.config.capture_scalar_outputs = True"
  1457. )
  1458. elif isinstance(
  1459. cause, torch._subclasses.fake_tensor.DynamicOutputShapeException
  1460. ):
  1461. if not torch._dynamo.config.capture_dynamic_output_shape_ops:
  1462. unimplemented(
  1463. f"dynamic shape operator: {cause.func}; "
  1464. "to enable, set torch._dynamo.config.capture_dynamic_output_shape_ops = True"
  1465. )
  1466. else:
  1467. unimplemented(
  1468. f"dynamic shape operator: {cause.func}; "
  1469. "Operator does not have a meta kernel that supports dynamic output shapes, "
  1470. "please report an issue to PyTorch"
  1471. )
  1472. elif isinstance(
  1473. cause, torch._subclasses.fake_tensor.UnsupportedOperatorException
  1474. ):
  1475. op = cause.func
  1476. import_suggestion = ""
  1477. if isinstance(op, torch._ops.OpOverload):
  1478. maybe_pystub = torch._C._dispatch_pystub(
  1479. op._schema.name, op._schema.overload_name
  1480. )
  1481. if maybe_pystub is not None:
  1482. module, ctx = maybe_pystub
  1483. import_suggestion = (
  1484. f"It's possible that the support was implemented in "
  1485. f"module `{module}` and you may need to `import {module}`"
  1486. f"({ctx}), otherwise "
  1487. )
  1488. unimplemented(
  1489. f"unsupported operator: {cause.func} ({import_suggestion}see "
  1490. "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0"
  1491. " for how to fix)"
  1492. )
  1493. elif isinstance(
  1494. cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode
  1495. ):
  1496. raise UserError( # noqa: B904
  1497. UserErrorType.CONSTRAINT_VIOLATION,
  1498. "Tried to use data-dependent value in the subsequent computation. "
  1499. "This can happen when we encounter unbounded dynamic value that is unknown during tracing time. "
  1500. "You will need to explicitly give hint to the compiler. Please take a look at "
  1501. f"torch._check OR torch._check_is_size APIs. {cause}",
  1502. case_name="constrain_as_size_example",
  1503. )
  1504. elif isinstance(cause, ValueRangeError):
  1505. raise UserError(UserErrorType.CONSTRAINT_VIOLATION, e.args[0]) from e
  1506. elif isinstance(cause, TypeError) and "argument" in str(cause):
  1507. unimplemented(f"TypeError {node.target}: {cause}")
  1508. raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
  1509. if not allow_non_graph_fake:
  1510. _ = pytree.tree_map_only(
  1511. torch.Tensor, functools.partial(ensure_graph_fake, tx=tx), ret_val
  1512. )
  1513. return ret_val
  1514. _current_node = threading.local()
  1515. def get_current_node():
  1516. return getattr(_current_node, "value", None)
  1517. @contextmanager
  1518. def set_current_node(node):
  1519. old = get_current_node()
  1520. _current_node.value = node
  1521. try:
  1522. yield
  1523. finally:
  1524. _current_node.value = old
  1525. def run_node(tracer, node, args, kwargs, nnmodule):
  1526. """
  1527. Runs a given node, with the given args and kwargs.
  1528. Behavior is dictated by a node's op.
  1529. run_node is useful for extracting real values out of nodes.
  1530. See get_real_value for more info on common usage.
  1531. Note: The tracer arg is only used for 'get_attr' ops
  1532. Note: The nnmodule arg is only used for 'call_module' ops
  1533. Nodes that are not call_function, call_method, call_module, or get_attr will
  1534. raise an AssertionError.
  1535. """
  1536. op = node.op
  1537. with set_current_node(node):
  1538. def make_error_message(e):
  1539. return f"Failed running {op} {node.target}(*{args}, **{kwargs}):\n" + str(e)
  1540. try:
  1541. if op == "call_function":
  1542. return node.target(*args, **kwargs)
  1543. elif op == "call_method":
  1544. return getattr(args[0], node.target)(*args[1:], **kwargs)
  1545. elif op == "call_module":
  1546. assert nnmodule is not None
  1547. return nnmodule(*args, **kwargs)
  1548. elif op == "get_attr":
  1549. return tracer.output_graph.get_submodule(node.target)
  1550. elif op == "placeholder":
  1551. assert "example_value" in node.meta
  1552. return node.meta["example_value"]
  1553. except (NotImplementedError, UnsupportedFakeTensorException) as e:
  1554. # NB: mimic how wrap_fake_exception does it
  1555. from .exc import unimplemented
  1556. unimplemented(make_error_message(e), from_exc=e)
  1557. except Exception as e:
  1558. raise RuntimeError(make_error_message(e)).with_traceback(
  1559. e.__traceback__
  1560. ) from e
  1561. raise AssertionError(op)
  1562. def get_real_value(node, tracer):
  1563. """
  1564. Run the actual computation represented by `node` and return the result.
  1565. This will execute any dependent nodes in the graph as well.
  1566. """
  1567. from .exc import TorchRuntimeError
  1568. cache = tracer.real_value_cache
  1569. if node in cache:
  1570. return cache[node]
  1571. op = node.op
  1572. args, kwargs = torch.fx.node.map_arg(
  1573. (node.args, node.kwargs),
  1574. lambda n: get_real_value(n, tracer),
  1575. )
  1576. if op == "placeholder" and "grapharg" in node.meta:
  1577. return node.meta["grapharg"].example
  1578. if op == "call_module":
  1579. nn_module = tracer.output_graph.nn_modules[node.target]
  1580. if not is_lazy_module(nn_module):
  1581. nn_module = copy.deepcopy(nn_module)
  1582. else:
  1583. # In the case of a lazy module, we want to run
  1584. # the pre-hooks which initialize it
  1585. nn_module(*args, **kwargs)
  1586. else:
  1587. nn_module = None
  1588. try:
  1589. real_value = run_node(tracer, node, args, kwargs, nn_module)
  1590. cache[node] = real_value
  1591. except RuntimeError as e:
  1592. raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
  1593. return real_value
  1594. def assert_no_fake_params_or_buffers(gm):
  1595. from torch._subclasses.fake_tensor import FakeTensorConfig, is_fake
  1596. def stack_or_hint(t):
  1597. if FakeTensorConfig.debug:
  1598. import traceback
  1599. return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}"
  1600. else:
  1601. return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors."
  1602. for name, buffer in gm.named_buffers():
  1603. assert not is_fake(
  1604. buffer
  1605. ), f"Unexpected fake buffer {name} {stack_or_hint(buffer)}"
  1606. for name, param in gm.named_parameters():
  1607. assert not is_fake(
  1608. param
  1609. ), f"Unexpected fake param {name} {stack_or_hint(param)}"
  1610. def fqn(obj: Any):
  1611. """
  1612. Returns the fully qualified name of the object.
  1613. """
  1614. return f"{obj.__module__}.{obj.__qualname__}"
  1615. def ifdynstaticdefault(count1, count2):
  1616. if torch._dynamo.config.assume_static_by_default:
  1617. return count1
  1618. else:
  1619. return count2
  1620. def import_submodule(mod: types.ModuleType):
  1621. """
  1622. Ensure all the files in a given submodule are imported
  1623. """
  1624. for filename in sorted(os.listdir(os.path.dirname(cast(str, mod.__file__)))):
  1625. if filename.endswith(".py") and filename[0] != "_":
  1626. importlib.import_module(f"{mod.__name__}.{filename[:-3]}")
  1627. def object_has_getattribute(value: Any):
  1628. try:
  1629. if isinstance(
  1630. inspect.getattr_static(type(value), "__getattribute__"),
  1631. types.FunctionType,
  1632. ):
  1633. return True
  1634. except AttributeError:
  1635. pass
  1636. return False
  1637. def get_custom_getattr(value: Any):
  1638. try:
  1639. getattr_fn = inspect.getattr_static(type(value), "__getattr__")
  1640. except AttributeError:
  1641. getattr_fn = None
  1642. if getattr_fn is torch.nn.Module.__getattr__:
  1643. # ignore this case of getattr
  1644. getattr_fn = None
  1645. return getattr_fn
  1646. class TensorStaticReason(enum.Enum):
  1647. PARAMETER = 2
  1648. NOT_TENSOR = 4
  1649. NN_MODULE_PROPERTY = 5
  1650. def tensor_static_reason_to_message(reason: TensorStaticReason):
  1651. if reason == TensorStaticReason.PARAMETER:
  1652. return "mark_dynamic on parameter, parameters are always static today."
  1653. if reason == TensorStaticReason.NOT_TENSOR:
  1654. return "mark_dynamic on a non tensor, how did this happen?"
  1655. if reason == TensorStaticReason.NN_MODULE_PROPERTY:
  1656. return "tensor is static because it is nn module associated."
  1657. raise AssertionError(f"Illegal reason {reason}")
  1658. def tensor_always_has_static_shape(
  1659. tensor: Union[torch.Tensor, Any],
  1660. is_tensor: bool,
  1661. guard_source: "torch._guards.GuardSource",
  1662. ) -> Tuple[bool, Optional[TensorStaticReason]]:
  1663. """
  1664. Given a tensor, source, and is_tensor flag, determine if a shape should be static.
  1665. Args:
  1666. tensor - the real tensor to evaluate, parameters force a static shape.
  1667. is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable,
  1668. tensors not in a TensorVariable for whatever reason are forced static.
  1669. Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape.
  1670. The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed.
  1671. """
  1672. if guard_source.is_nn_module() and config.force_nn_module_property_static_shapes:
  1673. return True, TensorStaticReason.NN_MODULE_PROPERTY
  1674. if type(tensor) is torch.nn.Parameter and config.force_parameter_static_shapes:
  1675. return True, TensorStaticReason.PARAMETER
  1676. if not is_tensor:
  1677. return True, TensorStaticReason.NOT_TENSOR
  1678. return False, None
  1679. def lazy_format_graph_tabular(fn_name, gm):
  1680. def inner():
  1681. try:
  1682. from tabulate import tabulate # TODO: Check that this is installed
  1683. except ImportError:
  1684. return (
  1685. "Tabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:\n"
  1686. + str(lazy_format_graph_code(fn_name, gm))
  1687. )
  1688. node_specs = [
  1689. [n.op, n.name, n.target, n.args, n.kwargs] for n in gm.graph.nodes
  1690. ]
  1691. graph_str = tabulate(
  1692. node_specs, headers=["opcode", "name", "target", "args", "kwargs"]
  1693. )
  1694. return _format_graph_code(fn_name, gm.forward.__code__.co_filename, graph_str)
  1695. return LazyString(inner)
  1696. def format_bytecode(prefix, name, filename, line_no, code):
  1697. return f"{prefix} {name} {filename} line {line_no} \n{dis.Bytecode(code).dis()}\n"
  1698. forward_hook_names = ["_forward_pre_hooks", "_forward_hooks"]
  1699. backward_hook_names = ["_backward_pre_hooks", "_backward_hooks"]
  1700. state_dict_hook_names = [
  1701. "_state_dict_pre_hooks",
  1702. "_state_dict_hooks",
  1703. "_load_state_dict_pre_hooks",
  1704. "_load_state_dict_post_hooks",
  1705. ]
  1706. all_hook_names = forward_hook_names + backward_hook_names + state_dict_hook_names
  1707. def nn_module_has_global_hooks():
  1708. # This is limited to backward hooks for now because NNModuleVariable
  1709. # supports fwd hooks underneath.
  1710. return len(torch.nn.modules.module._global_backward_hooks) or len(
  1711. torch.nn.modules.module._global_backward_pre_hooks
  1712. )
  1713. def nn_module_get_all_hooks(
  1714. mod,
  1715. check_forward_hooks=False,
  1716. check_backward_hooks=False,
  1717. check_state_dict_hooks=False,
  1718. ):
  1719. reset_code = torch._C._dynamo.eval_frame.reset_code
  1720. """
  1721. Sometimes its useful to differentiate between types of hooks such as forward/backward/pre
  1722. hooks executed during module.__call__, and state_dict hooks which are executed separately.
  1723. """
  1724. hook_dicts_to_check = []
  1725. check_all_hooks = (
  1726. not check_forward_hooks
  1727. and not check_backward_hooks
  1728. and not check_state_dict_hooks
  1729. )
  1730. if check_forward_hooks or check_all_hooks:
  1731. hook_dicts_to_check.extend(forward_hook_names)
  1732. if check_backward_hooks or check_all_hooks:
  1733. hook_dicts_to_check.extend(backward_hook_names)
  1734. if check_state_dict_hooks:
  1735. hook_dicts_to_check.extend(state_dict_hook_names)
  1736. all_hooks = []
  1737. for hook_dict_name in hook_dicts_to_check:
  1738. hooks = getattr(mod, hook_dict_name, [])
  1739. for hook_name in hooks:
  1740. hook = hooks[hook_name]
  1741. all_hooks.append(hook)
  1742. return all_hooks
  1743. def nnmodule_has_hooks(
  1744. mod,
  1745. check_forward_hooks=False,
  1746. check_backward_hooks=False,
  1747. check_state_dict_hooks=False,
  1748. ):
  1749. """
  1750. Helper function to check if a module has any hooks attached to it.
  1751. """
  1752. hooks = nn_module_get_all_hooks(
  1753. mod,
  1754. check_forward_hooks=check_forward_hooks,
  1755. check_backward_hooks=check_backward_hooks,
  1756. check_state_dict_hooks=check_state_dict_hooks,
  1757. )
  1758. return bool(hooks)
  1759. def to_numpy_helper(value):
  1760. """Convert tensor and tnp.ndarray to numpy.ndarray."""
  1761. if is_fake(value):
  1762. return value
  1763. if isinstance(value, tnp.ndarray):
  1764. return to_numpy_helper(value.tensor)
  1765. elif isinstance(value, torch.Tensor):
  1766. return value.numpy(force=True)
  1767. elif isinstance(value, (tuple, list)):
  1768. return type(value)(to_numpy_helper(obj) for obj in value)
  1769. else:
  1770. return value
  1771. def numpy_to_tensor(value):
  1772. """Convert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert."""
  1773. assert np is not None
  1774. if isinstance(value, np.ndarray):
  1775. return torch.as_tensor(value)
  1776. if isinstance(value, tnp.ndarray):
  1777. return value.tensor
  1778. elif isinstance(value, (tuple, list)):
  1779. return type(value)(numpy_to_tensor(obj) for obj in value)
  1780. else:
  1781. return value
  1782. class numpy_to_tensor_wrapper:
  1783. def __init__(self, f):
  1784. self.f = f
  1785. self.__name__ = "wrapped_" + self.f.__name__
  1786. def __repr__(self):
  1787. return f"<Wrapped function <original {self.f.__name__}>>"
  1788. def __call__(self, *args, **kwargs):
  1789. out = self.f(*args, **kwargs)
  1790. return numpy_to_tensor(out)
  1791. def numpy_attr_wrapper(obj, name):
  1792. if isinstance(obj, tnp.ndarray):
  1793. out = getattr(obj, name)
  1794. return numpy_to_tensor(out)
  1795. elif isinstance(obj, torch.Tensor):
  1796. out = getattr(tnp.ndarray(obj), name)
  1797. return numpy_to_tensor(out)
  1798. class numpy_method_wrapper:
  1799. """Convert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor."""
  1800. def __init__(self, method: str):
  1801. self.method = method
  1802. self.__name__ = "wrapped_" + self.method
  1803. def __repr__(self):
  1804. return f"<Wrapped method <original {self.method}>>"
  1805. def __call__(self, *args, **kwargs):
  1806. obj = args[0]
  1807. if isinstance(obj, torch.Tensor):
  1808. obj = tnp.ndarray(obj)
  1809. method_callable = getattr(obj, self.method)
  1810. out = method_callable(*args[1:], **kwargs)
  1811. return numpy_to_tensor(out)
  1812. class numpy_operator_wrapper:
  1813. """Implements dunder methods for tnp.ndarray via functions from the operator library"""
  1814. def __init__(self, op: Callable[..., Any]):
  1815. self.op = op
  1816. self.__name__ = f"wrapped_{op.__name__}"
  1817. def __repr__(self):
  1818. return f"<Wrapped operator <original {self.__name__}>>"
  1819. def __call__(self, *args, **kwargs):
  1820. assert not kwargs
  1821. args = (
  1822. tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args
  1823. )
  1824. out = self.op(*args)
  1825. return numpy_to_tensor(out)
  1826. def defake(x):
  1827. if not isinstance(x, FakeTensor):
  1828. return x
  1829. size: torch._prims_common.ShapeType
  1830. stride: torch._prims_common.StrideType
  1831. if x._has_symbolic_sizes_strides:
  1832. size = []
  1833. for s in x.size():
  1834. if isinstance(s, torch.SymInt):
  1835. size.append(s.node.shape_env.size_hint(s.node.expr))
  1836. else:
  1837. size.append(s)
  1838. stride = []
  1839. for s in x.stride():
  1840. if isinstance(s, torch.SymInt):
  1841. stride.append(s.node.shape_env.size_hint(s.node.expr))
  1842. else:
  1843. stride.append(s)
  1844. else:
  1845. size = x.size()
  1846. stride = x.stride()
  1847. y = torch.empty_strided(
  1848. size,
  1849. stride,
  1850. dtype=x.dtype,
  1851. device=x.device,
  1852. requires_grad=x.requires_grad,
  1853. )
  1854. y.zero_()
  1855. return y
  1856. def is_utils_checkpoint(obj):
  1857. # Lazy import to avoid circular dependencies
  1858. import torch.utils.checkpoint
  1859. return obj is torch.utils.checkpoint.checkpoint
  1860. def build_checkpoint_variable(**options):
  1861. import torch._higher_order_ops.wrap as higher_order_ops
  1862. from .variables.higher_order_ops import TorchHigherOrderOperatorVariable
  1863. # TODO - This is a temporary situation where we have two versions of
  1864. # checkpointing implementation. We will converge on one and remove the other.
  1865. activation_checkpoint_op: torch._ops.HigherOrderOperator = (
  1866. higher_order_ops.tag_activation_checkpoint
  1867. )
  1868. if torch._functorch.config.functionalize_rng_ops:
  1869. activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint
  1870. return TorchHigherOrderOperatorVariable.make(
  1871. activation_checkpoint_op,
  1872. **options,
  1873. )
  1874. def is_compile_supported(device_type):
  1875. from .eval_frame import is_dynamo_supported
  1876. compile_supported = is_dynamo_supported()
  1877. if device_type == "cpu":
  1878. pass
  1879. elif device_type == "cuda" and compile_supported:
  1880. compile_supported = has_triton()
  1881. else:
  1882. compile_supported = False
  1883. return compile_supported
  1884. # The following 3.11 source code functions are adapted from
  1885. # https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py
  1886. # in order to output source code corresponding to bytecode in 3.11+.
  1887. # We need our own versions since we want to support multiline expressions.
  1888. def _fix_offset(str: str, offset: int) -> int:
  1889. """
  1890. Convert byte offset `offset` of `str` into character offset.
  1891. Byte offset is used for 3.11+ instruction column data.
  1892. Takes things like unicode characters into consideration.
  1893. Unchanged from CPython implementation.
  1894. """
  1895. as_utf8 = str.encode("utf-8")
  1896. return len(as_utf8[:offset].decode("utf-8", errors="replace"))
  1897. @dataclasses.dataclass
  1898. class _Anchors:
  1899. # inclusive
  1900. left_end_lineno: int
  1901. left_end_offset: int
  1902. right_start_lineno: int
  1903. # exclusive
  1904. right_start_offset: int
  1905. def _extract_anchors_from_expr(segment: str) -> Optional[_Anchors]:
  1906. """
  1907. Given source code `segment` corresponding to a bytecode
  1908. instruction, determine:
  1909. - for binary ops, the location of the binary op
  1910. - for indexing, the location of the brackets.
  1911. `segment` is expected to be a valid Python expression
  1912. """
  1913. assert sys.version_info >= (3, 11)
  1914. import ast
  1915. try:
  1916. # Without brackets, `segment` is parsed as a statement.
  1917. # We expect an expression, so wrap `segment` in
  1918. # brackets to handle multi-line expressions.
  1919. tree = ast.parse("(\n" + segment + "\n)")
  1920. except SyntaxError:
  1921. return None
  1922. if len(tree.body) != 1:
  1923. return None
  1924. lines = segment.split("\n")
  1925. # get character index given byte offset
  1926. def normalize(lineno, offset):
  1927. return _fix_offset(lines[lineno], offset)
  1928. # Gets the next valid character index in `lines`, if
  1929. # the current location is not valid. Handles empty lines.
  1930. def next_valid_char(lineno, col):
  1931. while lineno < len(lines) and col >= len(lines[lineno]):
  1932. col = 0
  1933. lineno += 1
  1934. assert lineno < len(lines) and col < len(lines[lineno])
  1935. return lineno, col
  1936. # Get the next valid character index in `lines`.
  1937. def increment(lineno, col):
  1938. col += 1
  1939. lineno, col = next_valid_char(lineno, col)
  1940. assert lineno < len(lines) and col < len(lines[lineno])
  1941. return lineno, col
  1942. # Get the next valid character at least on the next line
  1943. def nextline(lineno, col):
  1944. col = 0
  1945. lineno += 1
  1946. lineno, col = next_valid_char(lineno, col)
  1947. assert lineno < len(lines) and col < len(lines[lineno])
  1948. return lineno, col
  1949. statement = tree.body[0]
  1950. if isinstance(statement, ast.Expr):
  1951. expr = statement.value
  1952. if isinstance(expr, ast.BinOp):
  1953. # ast gives locations for BinOp subexpressions, e.g.
  1954. # ( left_expr ) + ( right_expr )
  1955. # left^^^^^ right^^^^^
  1956. # -2 since end_lineno is 1-indexed and because we added an extra
  1957. # bracket to `segment` when calling ast.parse
  1958. cur_lineno = cast(int, expr.left.end_lineno) - 2
  1959. cur_col = normalize(cur_lineno, expr.left.end_col_offset)
  1960. cur_lineno, cur_col = next_valid_char(cur_lineno, cur_col)
  1961. # Heuristic to find the operator character.
  1962. # The original CPython implementation did not look for ), \, or #,
  1963. # leading to incorrect anchor location, e.g.
  1964. # (x) + (y)
  1965. # ~~^~~~~~~
  1966. while (ch := lines[cur_lineno][cur_col]).isspace() or ch in ")\\#":
  1967. if ch in "\\#":
  1968. cur_lineno, cur_col = nextline(cur_lineno, cur_col)
  1969. else:
  1970. cur_lineno, cur_col = increment(cur_lineno, cur_col)
  1971. # binary op is 1 or 2 characters long, on the same line
  1972. right_col = cur_col + 1
  1973. if (
  1974. right_col < len(lines[cur_lineno])
  1975. and not (ch := lines[cur_lineno][right_col]).isspace()
  1976. and ch not in "\\#"
  1977. ):
  1978. right_col += 1
  1979. # right_col can be invalid since it is exclusive
  1980. return _Anchors(cur_lineno, cur_col, cur_lineno, right_col)
  1981. elif isinstance(expr, ast.Subscript):
  1982. # ast gives locations for value and slice subexpressions, e.g.
  1983. # ( value_expr ) [ slice_expr ]
  1984. # value^^^^^ slice^^^^^
  1985. # subscript^^^^^^^^^^^^^^^^^^^^
  1986. # find left bracket (first '[' after value)
  1987. left_lineno = cast(int, expr.value.end_lineno) - 2
  1988. left_col = normalize(left_lineno, expr.value.end_col_offset)
  1989. left_lineno, left_col = next_valid_char(left_lineno, left_col)
  1990. while lines[left_lineno][left_col] != "[":
  1991. left_lineno, left_col = increment(left_lineno, left_col)
  1992. # find right bracket (final character of expression)
  1993. right_lineno = cast(int, expr.end_lineno) - 2
  1994. right_col = normalize(right_lineno, expr.end_col_offset)
  1995. return _Anchors(left_lineno, left_col, right_lineno, right_col)
  1996. elif isinstance(expr, ast.Call):
  1997. # ( func_expr ) (args, kwargs)
  1998. # func^^^^^
  1999. # call^^^^^^^^^^^^^^^^^^^^^^^^
  2000. # find left bracket (first '(' after func)
  2001. left_lineno = cast(int, expr.func.end_lineno) - 2
  2002. left_col = normalize(left_lineno, expr.func.end_col_offset)
  2003. left_lineno, left_col = next_valid_char(left_lineno, left_col)
  2004. while lines[left_lineno][left_col] != "(":
  2005. left_lineno, left_col = increment(left_lineno, left_col)
  2006. # find right bracket (final character of expression)
  2007. right_lineno = cast(int, expr.end_lineno) - 2
  2008. right_col = normalize(right_lineno, expr.end_col_offset)
  2009. return _Anchors(left_lineno, left_col, right_lineno, right_col)
  2010. return None
  2011. def get_instruction_source_311(code: types.CodeType, inst: dis.Instruction) -> str:
  2012. """
  2013. Python 3.11+ only. Returns lines of source code (from code object `code`)
  2014. corresponding to `inst`'s location data, and underlines relevant code to `inst`.
  2015. Example: CALL on `g`:
  2016. f(g(
  2017. ^^
  2018. h(x)))
  2019. ^^^^^
  2020. We need our own implementation since `format_frame_summary` in
  2021. Python's `traceback` module doesn't handle multi-line expressions
  2022. (and their anchor extraction code is not completely correct).
  2023. """
  2024. assert inst.positions is not None
  2025. if inst.positions.lineno is None:
  2026. return ""
  2027. # The rstrip + "\n" pattern is used throughout this function to handle
  2028. # linecache.getline errors. Error lines are treated as empty strings "", but we want
  2029. # to treat them as blank lines "\n".
  2030. first_line = linecache.getline(code.co_filename, inst.positions.lineno).rstrip()
  2031. if inst.positions.end_lineno is None:
  2032. return first_line
  2033. if inst.positions.col_offset is None or inst.positions.end_col_offset is None:
  2034. return first_line
  2035. # character index of the start of the instruction
  2036. start_offset = _fix_offset(first_line, inst.positions.col_offset)
  2037. # character index of the end of the instruction
  2038. # compute later since end may be a different line
  2039. end_offset = None
  2040. # expression corresponding to the instruction so we can get anchors
  2041. segment = ""
  2042. # underline markers to be printed - start with `~` marker and replace with `^` later
  2043. markers = []
  2044. # Compute segment and initial markers
  2045. if inst.positions.end_lineno == inst.positions.lineno:
  2046. end_offset = _fix_offset(first_line, inst.positions.end_col_offset)
  2047. segment = first_line[start_offset:end_offset]
  2048. markers.append(" " * start_offset + "~" * (end_offset - start_offset))
  2049. else:
  2050. segment = first_line[start_offset:] + "\n"
  2051. markers.append(" " * start_offset + "~" * (len(first_line) - start_offset))
  2052. last_line = linecache.getline(
  2053. code.co_filename, inst.positions.end_lineno
  2054. ).rstrip()
  2055. end_offset = _fix_offset(last_line, inst.positions.end_col_offset)
  2056. for lineno in range(inst.positions.lineno + 1, inst.positions.end_lineno):
  2057. line = linecache.getline(code.co_filename, lineno).rstrip()
  2058. segment += line + "\n"
  2059. # don't underline leading spaces
  2060. num_spaces = len(line) - len(line.lstrip())
  2061. markers.append(" " * num_spaces + "~" * (len(line) - num_spaces))
  2062. segment += last_line[:end_offset]
  2063. num_spaces = len(last_line) - len(last_line.lstrip())
  2064. markers.append(" " * num_spaces + "~" * (end_offset - num_spaces))
  2065. anchors: Optional[_Anchors] = None
  2066. try:
  2067. anchors = _extract_anchors_from_expr(segment)
  2068. except AssertionError:
  2069. pass
  2070. # replace `~` markers with `^` where necessary
  2071. if anchors is None:
  2072. markers = [marker.replace("~", "^") for marker in markers]
  2073. else:
  2074. # make markers mutable
  2075. mutable_markers: List[List[str]] = [list(marker) for marker in markers]
  2076. # anchor positions do not take start_offset into account
  2077. if anchors.left_end_lineno == 0:
  2078. anchors.left_end_offset += start_offset
  2079. if anchors.right_start_lineno == 0:
  2080. anchors.right_start_offset += start_offset
  2081. # Turn `~`` markers between anchors to `^`
  2082. for lineno in range(len(markers)):
  2083. for col in range(len(mutable_markers[lineno])):
  2084. if lineno < anchors.left_end_lineno:
  2085. continue
  2086. if lineno == anchors.left_end_lineno and col < anchors.left_end_offset:
  2087. continue
  2088. if (
  2089. lineno == anchors.right_start_lineno
  2090. and col >= anchors.right_start_offset
  2091. ):
  2092. continue
  2093. if lineno > anchors.right_start_lineno:
  2094. continue
  2095. if mutable_markers[lineno][col] == "~":
  2096. mutable_markers[lineno][col] = "^"
  2097. # make markers into strings again
  2098. markers = ["".join(marker) for marker in mutable_markers]
  2099. result = ""
  2100. for i in range(len(markers)):
  2101. result += (
  2102. linecache.getline(code.co_filename, inst.positions.lineno + i).rstrip()
  2103. + "\n"
  2104. )
  2105. result += markers[i] + "\n"
  2106. return result
  2107. def get_static_address_type(t):
  2108. if isinstance(t, torch.Tensor):
  2109. return getattr(t, "_dynamo_static_input_type", None)
  2110. return None
  2111. def is_rng_state_getter_or_setter(value):
  2112. getters = (
  2113. # The following two functions are not identical, so don't remove anyone!
  2114. torch._C.Generator.get_state,
  2115. torch.default_generator.get_state,
  2116. torch.get_rng_state,
  2117. torch.cuda.get_rng_state,
  2118. )
  2119. setters = (
  2120. torch._C.Generator.set_state,
  2121. torch.default_generator.set_state,
  2122. torch.set_rng_state,
  2123. torch.cuda.set_rng_state,
  2124. )
  2125. return value in (*setters, *getters)
  2126. def is_tensor_base_attr_getter(value):
  2127. return (
  2128. isinstance(value, types.MethodWrapperType)
  2129. and value.__name__ == "__get__"
  2130. and value.__self__.__objclass__ is torch._C._TensorBase # type: ignore[attr-defined]
  2131. )
  2132. def is_torch_function_object(value):
  2133. return hasattr(value, "__torch_function__")
  2134. def has_torch_function(vt: "torch._dynamo.variables.base.VariableTracker") -> bool:
  2135. from torch._dynamo.variables import LazyVariableTracker, UserDefinedObjectVariable
  2136. from torch._dynamo.variables.torch_function import TensorWithTFOverrideVariable
  2137. if isinstance(vt, TensorWithTFOverrideVariable):
  2138. return True
  2139. if isinstance(vt, LazyVariableTracker):
  2140. LazyVariableTracker.realize(vt)
  2141. return isinstance(vt, UserDefinedObjectVariable) and hasattr(
  2142. vt.value, "__torch_function__"
  2143. )
  2144. # see note [Tensor Fakification and Symbol Caching]
  2145. def to_fake_tensor(t, fake_mode):
  2146. symbolic_context = None
  2147. source = None
  2148. if tracing_context := torch._guards.TracingContext.try_get():
  2149. if t in tracing_context.tensor_to_context:
  2150. symbolic_context = tracing_context.tensor_to_context[t]
  2151. source = symbolic_context.tensor_source
  2152. return fake_mode.from_tensor(
  2153. t, static_shapes=False, symbolic_context=symbolic_context, source=source
  2154. )
  2155. def get_first_attr(obj, *attrs):
  2156. """
  2157. Return the first available attribute or throw an exception if none is present.
  2158. """
  2159. for attr in attrs:
  2160. if hasattr(obj, attr):
  2161. return getattr(obj, attr)
  2162. raise AssertionError(f"{obj} does not has any of the attributes: {attrs}")
  2163. @contextlib.contextmanager
  2164. def maybe_enable_compiled_autograd(should_enable):
  2165. def compiler_fn(gm):
  2166. def inner_compiler(gm_, example_inputs_):
  2167. torch._dynamo.utils.counters["compiled_autograd"]["compiles"] += 1
  2168. return torch._inductor.compile(gm_, example_inputs_)
  2169. return torch.compile(gm, backend=inner_compiler, fullgraph=True, dynamic=True)
  2170. if should_enable:
  2171. with torch._dynamo.compiled_autograd.enable(compiler_fn) as ctx:
  2172. yield ctx
  2173. else:
  2174. yield
  2175. def invalid_removeable_handle():
  2176. # need a subclass so weakref works
  2177. class Invalid(dict): # type: ignore[type-arg]
  2178. pass
  2179. return RemovableHandle(Invalid())
  2180. # Returns a "proxy" (new object with the same class and dict) for (non-GraphModule) nn.Module's.
  2181. # Attribute changes to the original object/proxy will be reflected in the other.
  2182. # This is useful for cases where we want a keep-alive reference to a module without increasing
  2183. # its reference count.
  2184. def nn_module_proxy(mod):
  2185. if not isinstance(mod, torch.nn.Module):
  2186. return mod
  2187. if isinstance(mod, torch.fx.GraphModule):
  2188. # Dynamo-generated GM's shouldn't contain user-created GM's
  2189. return mod
  2190. proxy = mod.__class__.__new__(mod.__class__)
  2191. proxy.__dict__ = mod.__dict__
  2192. return proxy
  2193. class GmWrapper(torch.nn.Module):
  2194. def __init__(self, gm, spec):
  2195. super().__init__()
  2196. self.gm = gm
  2197. self.spec = spec
  2198. def forward(self, *args):
  2199. args: List[Any] = list(args)
  2200. return self.gm(*pytree.tree_unflatten(args, self.spec))
  2201. def flatten_graph_inputs(gm: torch.fx.GraphModule, inputs, compile_gm):
  2202. """
  2203. Mutate inputs so that they are flat and wrap gm such that it
  2204. accepts those inputs. This is needed for graphs that take
  2205. bumpy inputs.
  2206. """
  2207. inputs, spec = pytree.tree_flatten(inputs)
  2208. compiled_fn = compile_gm(GmWrapper(gm, spec), inputs)
  2209. idx_to_steal = [
  2210. i
  2211. for i, node in enumerate(gm.graph.nodes)
  2212. if node.op == "placeholder" and node.meta.get("steal_arg", False)
  2213. ]
  2214. def wrapper(*args):
  2215. # note this doesn't check the spec, assuming it is the same
  2216. flat_args = pytree.arg_tree_leaves(*args)
  2217. # flat_args is a new list, so we need to clear references from the old list
  2218. for i in idx_to_steal:
  2219. args[i].clear()
  2220. # this call is boxed to avoid increasing refcount until we reach aot_module_simplified forward
  2221. return compiled_fn(flat_args)
  2222. return wrapper
  2223. def get_locals_to_steal(maybe_gm):
  2224. if not isinstance(maybe_gm, torch.fx.GraphModule) or not hasattr(maybe_gm, "meta"):
  2225. return []
  2226. return maybe_gm.meta.get("locals_to_steal", [])
  2227. def set_locals_to_steal(gm, locals_to_steal):
  2228. gm.meta["locals_to_steal"] = locals_to_steal
  2229. class Lit:
  2230. def __init__(self, s):
  2231. self.s = s
  2232. def __repr__(self):
  2233. return self.s
  2234. warn_once_cache: Set[str] = set()
  2235. def warn_once(msg, stacklevel=1):
  2236. # Dynamo causes all warnings.warn (in user code and in Dynamo code) to print all the time.
  2237. # https://github.com/pytorch/pytorch/issues/128427.
  2238. # warn_once is a workaround: if the msg has been warned on before, then we will not
  2239. # warn again.
  2240. # NB: it's totally ok to store a cache of all the strings: this is what warnings.warn does as well.
  2241. if msg in warn_once_cache:
  2242. return
  2243. warn_once_cache.add(msg)
  2244. warnings.warn(msg, stacklevel=stacklevel + 1)