utils.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  1. import collections
  2. import contextlib
  3. import copy
  4. import cProfile
  5. import dataclasses
  6. import datetime
  7. import dis
  8. import enum
  9. import functools
  10. import gc
  11. import inspect
  12. import itertools
  13. import logging.config
  14. import math
  15. import operator
  16. import os
  17. import pstats
  18. import re
  19. import sys
  20. import time
  21. import types
  22. import typing
  23. import weakref
  24. from contextlib import contextmanager
  25. from functools import lru_cache, wraps
  26. from typing import Any, Dict, List
  27. try:
  28. import numpy as np
  29. HAS_NUMPY = True
  30. except ModuleNotFoundError:
  31. np = None # type: ignore[assignment]
  32. HAS_NUMPY = False
  33. import importlib
  34. import torch
  35. import torch.fx.experimental.symbolic_shapes
  36. from torch import fx
  37. from torch._dispatch.python import enable_python_dispatcher
  38. from torch._subclasses.fake_tensor import FakeTensor
  39. from torch.nn.modules.lazy import LazyModuleMixin
  40. from torch.utils._pytree import tree_flatten, tree_map
  41. from . import config, logging as torchdynamo_logging
  42. counters = collections.defaultdict(collections.Counter)
  43. troubleshooting_url = "https://pytorch.org/docs/master/dynamo/troubleshooting.html"
  44. log = logging.getLogger(__name__)
  45. # profiling compilation time
  46. compilation_metrics = collections.OrderedDict()
  47. timer_counter = itertools.count()
  48. def tabulate(rows, headers):
  49. try:
  50. import tabulate
  51. return tabulate.tabulate(rows, headers=headers)
  52. except ImportError:
  53. return "\n".join(
  54. ", ".join(map(str, row)) for row in itertools.chain([headers], rows)
  55. )
  56. def dynamo_profiled(func):
  57. @wraps(func)
  58. def profile_wrapper(*args, **kwargs):
  59. global timer_counter
  60. datafn = (
  61. func.__name__ + f"{next(timer_counter)}.profile"
  62. ) # Name the data file sensibly
  63. prof = cProfile.Profile()
  64. prof.enable()
  65. retval = prof.runcall(func, *args, **kwargs)
  66. prof.disable()
  67. print(f"### Cprofile for {func.__name__} iter {next(timer_counter)} ###")
  68. ps = pstats.Stats(prof)
  69. ps.sort_stats(pstats.SortKey.TIME).print_stats(20)
  70. ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)
  71. prof.dump_stats(datafn)
  72. return retval
  73. return profile_wrapper
  74. frame_phase_timing = collections.OrderedDict()
  75. curr_frame = 0
  76. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  77. def increment_frame():
  78. global curr_frame
  79. curr_frame = curr_frame + 1
  80. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  81. def reset_frame_count():
  82. global curr_frame
  83. frame_phase_timing.clear()
  84. curr_frame = 0
  85. op_count = 0
  86. def increment_op_count(cnt):
  87. global op_count
  88. op_count += cnt
  89. # Print a report of time spent so far
  90. # Ex:
  91. # TIMING:
  92. # entire_frame_compile:8.574629999999999
  93. # backend_compile:5.26806
  94. def print_time_report():
  95. total = 0
  96. total_by_key = {}
  97. for frame, timings in frame_phase_timing.items():
  98. for key, timing in timings.items():
  99. total += timing
  100. if key not in total_by_key:
  101. total_by_key[key] = timing
  102. else:
  103. total_by_key[key] += timing
  104. out = "TIMING:"
  105. for key, value in total_by_key.items():
  106. out = f"{out} {key}:{round(value, 5)}"
  107. print(out)
  108. # dynamo_timed API works as a function decorator
  109. # By wrapping a function in dynamo_timed, we can store a record in compilation_metrics
  110. # where the key is the functions name.
  111. # For example:
  112. #
  113. # @dynamo_timed
  114. # def _foo(...):
  115. #
  116. # Would show up as an entry in our timing dict:
  117. # OrderedDict([('bar.<locals>._foo', [0.083690, 0.23949, 3.1425e-05])])
  118. # This is extremely useful for granular debugging.
  119. #
  120. # For a higher-level mode, pass a phase_name into dynamo_timed
  121. # phase_names record an extra record into a separate compilation timing structure,
  122. # one keyed on frame+name rather than function.
  123. # The frame is incremented outside of this function, in def increment_frame() above.
  124. def dynamo_timed(original_function=None, phase_name=None):
  125. def dynamo_timed_inner(func):
  126. @wraps(func)
  127. def time_wrapper(*args, **kwargs):
  128. key = func.__qualname__
  129. if key not in compilation_metrics:
  130. compilation_metrics[key] = []
  131. t0 = time.time()
  132. r = func(*args, **kwargs)
  133. time_spent = time.time() - t0
  134. # print(f"Dynamo timer: key={key}, latency={latency:.2f} sec")
  135. compilation_metrics[key].append(time_spent)
  136. if phase_name:
  137. frame_key = str(curr_frame)
  138. if frame_key not in frame_phase_timing:
  139. frame_phase_timing[frame_key] = {}
  140. assert (
  141. phase_name not in frame_phase_timing[frame_key]
  142. ), f"Duplicate phase name {phase_name} for frame {frame_key}"
  143. frame_phase_timing[frame_key][phase_name] = time_spent
  144. return r
  145. return time_wrapper
  146. if original_function:
  147. return dynamo_timed_inner(original_function)
  148. return dynamo_timed_inner
  149. def compile_times(repr="str", aggregate=False):
  150. """
  151. Get metrics about torchdynamo frontend/backend compilation times.
  152. Accumulates information from functions tagged with `@dynamo_timed`.
  153. repr='str' returns a printable string for user interaction, and 'csv'
  154. returns headers, rows which can be logged for output
  155. aggregate causes values from multiple compilations (e.g. split graphs)
  156. to be accumulated into one value. If false, expect more than one value
  157. per metric.
  158. """
  159. def fmt_fn(values, item_fn=lambda x: x):
  160. if aggregate:
  161. return item_fn(sum(values))
  162. return ", ".join(map(item_fn, values))
  163. if repr == "str":
  164. rows = [
  165. (k, fmt_fn(compilation_metrics[k], item_fn=lambda x: f"{x:.4f}"))
  166. for k in compilation_metrics
  167. ]
  168. out = "TorchDynamo compilation metrics:\n"
  169. out += tabulate(rows, headers=("Function", "Runtimes (s)"))
  170. return out
  171. elif repr == "csv":
  172. values = [
  173. fmt_fn(v, item_fn=lambda x: f"{x:.6f}")
  174. for v in compilation_metrics.values()
  175. ]
  176. headers = list(compilation_metrics.keys())
  177. return headers, values
  178. tensortype_to_dtype = {
  179. torch.FloatTensor: (torch.float32, torch.float),
  180. torch.DoubleTensor: (torch.float64, torch.double),
  181. torch.HalfTensor: (torch.float16, torch.half),
  182. torch.BFloat16Tensor: (torch.bfloat16,),
  183. torch.ByteTensor: (torch.uint8,),
  184. torch.CharTensor: (torch.int8,),
  185. torch.LongTensor: (torch.int64, torch.long),
  186. torch.IntTensor: (torch.int32, torch.int),
  187. torch.ShortTensor: (torch.int16, torch.short),
  188. torch.BoolTensor: (torch.bool,),
  189. }
  190. class DuplicateWarningChecker:
  191. def __init__(self, maxsize=4096):
  192. self.maxsize = maxsize
  193. self.reset()
  194. def reset(self):
  195. self.set = collections.OrderedDict()
  196. def add(self, key):
  197. if key in self.set:
  198. self.set.move_to_end(key, last=True)
  199. if not config.verbose:
  200. return False
  201. else:
  202. self.set[key] = None
  203. while len(self.set) > self.maxsize:
  204. self.set.popitem(last=False)
  205. return True
  206. graph_break_dup_warning_checker = DuplicateWarningChecker()
  207. def init_logging():
  208. torchdynamo_logging.init_logging(
  209. config.log_level, log_file_name=config.log_file_name
  210. )
  211. graph_break_dup_warning_checker.reset()
  212. def format_graph_tabular(graph):
  213. node_specs = [[n.op, n.name, n.target, n.args, n.kwargs] for n in graph.nodes]
  214. return tabulate(node_specs, headers=["opcode", "name", "target", "args", "kwargs"])
  215. def format_bytecode(prefix, name, filename, line_no, code):
  216. return f"{prefix} {name} {filename}\
  217. line {line_no} \n{dis.Bytecode(code).dis()}\n "
  218. def gen_record_file_name(exc, code):
  219. return f"{get_debug_dir()}/error_recordings/\
  220. {code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec"
  221. def write_record_to_file(filename, exec_record):
  222. try:
  223. if os.path.exists(filename):
  224. log.warning(
  225. f"Unable to write execution record {filename}; file already exists."
  226. )
  227. else:
  228. os.makedirs(os.path.dirname(filename), exist_ok=True)
  229. with open(filename, "wb") as f:
  230. exec_record.dump(f)
  231. except Exception:
  232. log.error(f"Unable to write execution record {filename}", exc_info=1)
  233. def count_calls(g: fx.Graph):
  234. c = 0
  235. for n in g.nodes:
  236. if "call" in n.op:
  237. c += 1
  238. return c
  239. def identity(x):
  240. return x
  241. def nothing(*args, **kwargs):
  242. pass
  243. class ExactWeakKeyDictionary:
  244. """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality"""
  245. def __init__(self):
  246. self.values = dict()
  247. self.refs = dict()
  248. def __getitem__(self, key):
  249. return self.values[id(key)]
  250. def get(self, key, default=None):
  251. return self.values.get(id(key), default)
  252. def __contains__(self, key):
  253. return id(key) in self.values
  254. def __setitem__(self, key, value):
  255. idx = id(key)
  256. if idx not in self.refs:
  257. self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx))
  258. self.values[idx] = value
  259. def _remove_id(self, idx):
  260. if idx in self.values:
  261. del self.values[idx]
  262. if idx in self.refs:
  263. del self.refs[idx]
  264. def clear(self):
  265. self.refs.clear()
  266. self.values.clear()
  267. def istype(obj, allowed_types):
  268. """isinstance() without subclasses"""
  269. if isinstance(allowed_types, (tuple, list, set)):
  270. return type(obj) in allowed_types
  271. return type(obj) is allowed_types
  272. def is_typing(value):
  273. if sys.version_info < (3, 9):
  274. return isinstance(value, typing._GenericAlias)
  275. else:
  276. return isinstance(value, typing._SpecialGenericAlias)
  277. def is_numpy_int_type(value):
  278. if HAS_NUMPY:
  279. return istype(
  280. value,
  281. (
  282. np.int8,
  283. np.int16,
  284. np.int32,
  285. np.int64,
  286. np.uint8,
  287. np.uint16,
  288. np.uint32,
  289. np.uint64,
  290. ),
  291. )
  292. else:
  293. return False
  294. def is_numpy_float_type(value):
  295. if HAS_NUMPY:
  296. return istype(
  297. value,
  298. (
  299. np.float16,
  300. np.float32,
  301. np.float64,
  302. ),
  303. )
  304. else:
  305. return False
  306. def is_numpy_ndarray(value):
  307. if HAS_NUMPY:
  308. return istype(value, np.ndarray)
  309. else:
  310. return False
  311. def istensor(obj):
  312. """Check of obj is a tensor"""
  313. tensor_list = (
  314. torch.Tensor,
  315. torch.nn.Parameter,
  316. *config.traceable_tensor_subclasses,
  317. )
  318. tensor_list = tensor_list + (torch._subclasses.FakeTensor,)
  319. return istype(obj, tensor_list)
  320. def is_lazy_module(mod):
  321. return isinstance(mod, LazyModuleMixin)
  322. @functools.lru_cache(4096)
  323. def print_once(*args):
  324. print(*args)
  325. def make_cell(val=None):
  326. """Some black magic to create a cell object that usually only exists in a closure"""
  327. x = val
  328. def f():
  329. return x
  330. assert len(f.__closure__) == 1
  331. return f.__closure__[0]
  332. def proxy_args_kwargs(args, kwargs):
  333. try:
  334. proxy_args = tuple(arg.as_proxy() for arg in args)
  335. proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()}
  336. return proxy_args, proxy_kwargs
  337. except NotImplementedError as e:
  338. from .exc import unimplemented
  339. from .variables.base import typestr
  340. raise unimplemented(
  341. f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}"
  342. ) from e
  343. @dataclasses.dataclass
  344. class CleanupHook:
  345. """Remove a global variable when hook is called"""
  346. scope: Dict[str, Any]
  347. name: str
  348. def __call__(self, *args):
  349. CleanupManager.count -= 1
  350. del self.scope[self.name]
  351. @staticmethod
  352. def create(scope, name, val):
  353. assert name not in scope
  354. CleanupManager.count += 1
  355. scope[name] = val
  356. return CleanupHook(scope, name)
  357. class CleanupManager(ExactWeakKeyDictionary):
  358. count = 0
  359. def _remove_id(self, idx):
  360. for hook in self.values[idx]:
  361. hook()
  362. super()._remove_id(idx)
  363. CleanupManager.instance = CleanupManager()
  364. def clone_tensor(x):
  365. """Clone the tensor and its gradient"""
  366. y = x.clone().requires_grad_(x.requires_grad)
  367. if x.is_leaf and x.grad is not None:
  368. y.grad = x.grad.clone()
  369. return y
  370. def clone_input(x):
  371. """copy while preserving strides"""
  372. # TODO: this is questionable
  373. if isinstance(x, torch._subclasses.FakeTensor):
  374. # this func fails on fake tensors in __torch_dispatch__
  375. return x
  376. def torch_clone(x):
  377. y = torch.clone(x)
  378. if x.is_leaf:
  379. y.requires_grad_(x.requires_grad)
  380. if x.is_leaf and x.grad is not None:
  381. y.grad = clone_input(x.grad)
  382. return y
  383. with torch.no_grad():
  384. if x.device.type == "xla":
  385. # Access data_ptr() for a xla tensor will cause crash
  386. return torch_clone(x)
  387. needed_size = sum(
  388. (shape - 1) * stride for shape, stride in zip(x.size(), x.stride())
  389. )
  390. if x.is_quantized:
  391. result = torch.empty_quantized((needed_size + 32,), x)
  392. else:
  393. result = torch.empty(needed_size + 32, dtype=x.dtype, device=x.device)
  394. cache_line_offset = (
  395. (x.data_ptr() - result.data_ptr()) % 32
  396. ) // x.element_size()
  397. result.as_strided_(x.size(), x.stride(), cache_line_offset)
  398. try:
  399. result.copy_(x.clone())
  400. if x.is_leaf:
  401. result.requires_grad_(x.requires_grad)
  402. if x.is_leaf and x.grad is not None:
  403. result.grad = clone_input(x.grad)
  404. except RuntimeError:
  405. # RuntimeError: unsupported operation: more than one element of the written-to
  406. # tensor refers to a single memory location. Please clone() the tensor before
  407. # performing the operation.
  408. return torch_clone(x)
  409. return result
  410. def clone_inputs(example_inputs):
  411. if isinstance(example_inputs, dict):
  412. res = dict(example_inputs)
  413. for key, value in res.items():
  414. assert isinstance(value, torch.Tensor)
  415. res[key] = clone_input(value)
  416. return res
  417. res = list(example_inputs)
  418. for i in range(len(res)):
  419. if isinstance(res[i], torch.Tensor):
  420. res[i] = clone_input(res[i])
  421. return res
  422. @contextmanager
  423. def preserve_rng_state():
  424. rng = torch.clone(torch.random.get_rng_state())
  425. if torch.cuda.is_available():
  426. cuda_rng = torch.clone(torch.cuda.get_rng_state())
  427. try:
  428. yield
  429. finally:
  430. torch.random.set_rng_state(rng)
  431. if torch.cuda.is_available():
  432. torch.cuda.set_rng_state(cuda_rng)
  433. def is_jit_model(model0):
  434. return isinstance(
  435. model0,
  436. (
  437. torch.jit._trace.TopLevelTracedModule,
  438. torch.jit._script.RecursiveScriptModule,
  439. torch.jit.ScriptFunction,
  440. torch.jit.ScriptModule,
  441. ),
  442. )
  443. def torchscript(model, example_inputs, verbose=False):
  444. if is_jit_model(model):
  445. # already done?
  446. return model
  447. try:
  448. return torch.jit.trace(model, example_inputs)
  449. except Exception:
  450. try:
  451. return torch.jit.script(model)
  452. except Exception:
  453. if verbose:
  454. log.exception("jit error")
  455. else:
  456. log.error("Both torch.jit.trace and torch.jit.script failed")
  457. return None
  458. def getfile(obj):
  459. try:
  460. return inspect.getfile(obj)
  461. except TypeError:
  462. return None
  463. def is_namedtuple(obj):
  464. """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
  465. return is_namedtuple_cls(type(obj))
  466. def is_namedtuple_cls(cls):
  467. """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
  468. try:
  469. if issubclass(cls, tuple):
  470. bases = getattr(cls, "__bases__", []) or [None]
  471. module = getattr(cls, "__module__", None)
  472. return module == "torch.return_types" or (
  473. bases[0] is tuple and hasattr(cls, "_make") and hasattr(cls, "_fields")
  474. )
  475. except TypeError:
  476. pass
  477. return False
  478. @functools.lru_cache(1)
  479. def namedtuple_fields(cls):
  480. """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple"""
  481. if cls is slice:
  482. return ["start", "stop", "step"]
  483. assert issubclass(cls, tuple)
  484. if hasattr(cls, "_fields"):
  485. # normal namedtuples
  486. return cls._fields
  487. @dataclasses.dataclass
  488. class Marker:
  489. index: int
  490. # frustrating ones e.g. torch.return_types.max
  491. assert cls.__module__ == "torch.return_types"
  492. obj = cls(map(Marker, range(cls.n_fields)))
  493. fields = [None] * cls.n_fields
  494. for name in dir(obj):
  495. if name[0] != "_" and isinstance(getattr(obj, name), Marker):
  496. fields[getattr(obj, name).index] = name
  497. return fields
  498. def checkpoint_params(gm):
  499. with torch.no_grad():
  500. rng_state = torch.clone(torch.random.get_rng_state())
  501. if torch.cuda.is_available():
  502. cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
  503. saved_state = []
  504. for param in itertools.chain(gm.parameters(), gm.buffers()):
  505. saved_state.append((param, param._version, torch.clone(param)))
  506. def restore():
  507. with torch.no_grad():
  508. torch.random.set_rng_state(rng_state)
  509. if torch.cuda.is_available():
  510. torch.cuda.set_rng_state(cuda_rng_state)
  511. for param, version, original_value in saved_state:
  512. if param._version != version:
  513. param.copy_(original_value)
  514. return restore
  515. def timed(model, example_inputs, times=1):
  516. if torch.cuda.is_available():
  517. synchronize = torch.cuda.synchronize
  518. else:
  519. synchronize = nothing
  520. synchronize()
  521. gc.collect()
  522. torch.manual_seed(1337)
  523. t0 = time.perf_counter()
  524. for _ in range(times):
  525. result = model(*example_inputs)
  526. synchronize()
  527. t1 = time.perf_counter()
  528. return result, t1 - t0
  529. def check_is_cuda(gm, example_inputs):
  530. return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True)))
  531. @lru_cache(32)
  532. def rot_n_helper(n):
  533. assert n > 1
  534. vars = [f"v{i}" for i in range(n)]
  535. rotated = reversed(vars[-1:] + vars[:-1])
  536. fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})")
  537. fn.__name__ = f"rot_{n}_helper"
  538. return fn
  539. def is_safe_constant(v):
  540. if istype(v, (tuple, frozenset)):
  541. return all(map(is_safe_constant, v))
  542. return istype(
  543. v,
  544. (
  545. types.CodeType,
  546. int,
  547. float,
  548. bool,
  549. str,
  550. bytes,
  551. type(None),
  552. slice,
  553. type(type),
  554. torch.device,
  555. torch.dtype,
  556. ),
  557. ) or isinstance(v, enum.Enum)
  558. def check_constant_args(args, kwargs):
  559. return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values()))
  560. def check_unspec_python_args(args, kwargs):
  561. from .variables.constant import ConstantVariable
  562. from .variables.tensor import UnspecializedPythonVariable
  563. unspec_count = 0
  564. for x in itertools.chain(args, kwargs.values()):
  565. if isinstance(x, UnspecializedPythonVariable):
  566. unspec_count += 1
  567. elif not isinstance(x, (UnspecializedPythonVariable, ConstantVariable)):
  568. return False
  569. else:
  570. pass
  571. return unspec_count > 0
  572. def specialize_args_kwargs(tx, args, kwargs):
  573. specialized_args = []
  574. specialized_kwargs = {}
  575. for x in args:
  576. specialized_args.append(x.as_specialized(tx))
  577. for k, v in kwargs.items():
  578. specialized_kwargs.update({k: v.as_specialized(tx)})
  579. return specialized_args, specialized_kwargs
  580. dict_values = type(dict().values())
  581. odict_values = type(collections.OrderedDict().values())
  582. tuple_iterator = type(iter(tuple()))
  583. tuple_iterator_len = tuple_iterator.__length_hint__
  584. object_new = object.__new__
  585. def product(it):
  586. return functools.reduce(operator.mul, it, 1)
  587. def tuple_iterator_getitem(it, index):
  588. _, (obj,), start = it.__reduce__()
  589. return obj[start + index]
  590. def enum_repr(value):
  591. # Workaround repr(Enum) returning invalid global reference before python 3.11
  592. # https://peps.python.org/pep-0663/
  593. if sys.version_info < (3, 11):
  594. return str(value)
  595. else:
  596. return repr(value)
  597. def dict_param_key_ids(value):
  598. return {id(k) for k in value.keys() if isinstance(k, torch.nn.Parameter)}
  599. def dict_const_keys(value):
  600. return {k for k in value.keys() if not isinstance(k, torch.nn.Parameter)}
  601. def dict_const_keys_repr(const_keys):
  602. if any(isinstance(k, enum.Enum) for k in const_keys):
  603. # To workaround repr(Enum) returning invalid global reference before python 3.11
  604. # by calling enum_repr and removing quotes to render enum in guard code.
  605. const_keys_str = f"{ {enum_repr(k) if isinstance(k, enum.Enum) else repr(k) for k in const_keys} }".replace(
  606. "'", ""
  607. )
  608. else:
  609. const_keys_str = f"{const_keys!r}"
  610. return const_keys_str
  611. def global_key_name(key):
  612. return f"__dict_key_{id(key)}"
  613. def rename_implicit(v):
  614. """
  615. Usage of inline comprehensions generates a implicit ".0" variable that
  616. trips up guard generation. This renames these variables in guards.
  617. """
  618. m = re.match(r"^[.](\d+)$", v)
  619. if m:
  620. assert v == ".0", f"currently only .0 supported: {v}"
  621. # to support .1 etc see guards.py and _eval_frame.c
  622. return f"___implicit{m.group(1)}"
  623. return v
  624. from torch._subclasses import ( # noqa: F401
  625. FakeTensorMode,
  626. UnsupportedFakeTensorException,
  627. )
  628. def wrap_fake_exception(fn):
  629. try:
  630. return fn()
  631. except UnsupportedFakeTensorException as e:
  632. from .exc import unimplemented
  633. msg = f"Unsupported: {e.reason} with fake tensor propagation."
  634. log.warning(msg)
  635. raise unimplemented(msg) from e
  636. def deepcopy_to_fake_tensor(obj, fake_mode):
  637. with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode):
  638. return wrap_fake_exception(lambda: copy.deepcopy(obj))
  639. def rmse(ref, res):
  640. """
  641. Calculate root mean squared error
  642. """
  643. return torch.sqrt(torch.mean(torch.square(ref - res)))
  644. def same(
  645. ref,
  646. res,
  647. fp64_ref=None,
  648. cos_similarity=False,
  649. tol=1e-4,
  650. equal_nan=False,
  651. exact_dtype=True,
  652. relax_numpy_equality=False,
  653. ):
  654. """Check correctness to see if ref and res match"""
  655. if fp64_ref is None:
  656. fp64_ref = ref
  657. if isinstance(ref, (list, tuple, torch.nn.ParameterList, torch.Size)):
  658. assert isinstance(res, (list, tuple)), f"type mismatch {type(ref)} {type(res)}"
  659. return len(ref) == len(res) and all(
  660. same(
  661. ai,
  662. bi,
  663. fp64_refi,
  664. cos_similarity,
  665. tol,
  666. equal_nan,
  667. exact_dtype,
  668. relax_numpy_equality,
  669. )
  670. for ai, bi, fp64_refi in zip(ref, res, fp64_ref)
  671. )
  672. elif isinstance(ref, dict):
  673. assert isinstance(res, dict)
  674. assert set(ref.keys()) == set(
  675. res.keys()
  676. ), f"keys mismatch {set(ref.keys())} == {set(res.keys())}"
  677. for k in ref.keys():
  678. if not (
  679. same(
  680. ref[k],
  681. res[k],
  682. fp64_ref[k],
  683. cos_similarity=cos_similarity,
  684. tol=tol,
  685. equal_nan=equal_nan,
  686. exact_dtype=exact_dtype,
  687. relax_numpy_equality=relax_numpy_equality,
  688. )
  689. ):
  690. log.error(f"Accuracy failed for key name {k}")
  691. return False
  692. return True
  693. elif isinstance(ref, torch.Tensor):
  694. assert not isinstance(ref, torch._subclasses.FakeTensor)
  695. assert not isinstance(res, torch._subclasses.FakeTensor)
  696. if ref.is_sparse:
  697. assert res.is_sparse
  698. ref = ref.to_dense()
  699. res = res.to_dense()
  700. assert isinstance(res, torch.Tensor), f"type mismatch {type(ref)} {type(res)}"
  701. if exact_dtype:
  702. if ref.dtype != res.dtype:
  703. log.error(f"dtype mismatch {ref.dtype}, {res.dtype}")
  704. return False
  705. if ref.dtype == torch.bool:
  706. # triton stores bool as int8, so add this for more accurate checking
  707. r = torch.allclose(
  708. ref.to(dtype=torch.uint8),
  709. res.to(dtype=torch.uint8),
  710. atol=tol,
  711. rtol=tol,
  712. equal_nan=equal_nan,
  713. )
  714. if not r:
  715. log.error("Accuracy failed: uint8 tensor did not match")
  716. return r
  717. if cos_similarity:
  718. ref = ref.flatten().to(torch.float32)
  719. res = res.flatten().to(torch.float32)
  720. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True):
  721. # early exit that handles zero/nan better
  722. # cosine_similarity(zeros(10), zeros(10), dim=0) is 0
  723. return True
  724. score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6)
  725. if score < 0.99:
  726. log.warning(f"Similarity score={score.cpu().detach().item()}")
  727. return score >= 0.99
  728. else:
  729. if not exact_dtype:
  730. ref = ref.to(res.dtype)
  731. # First try usual allclose
  732. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan):
  733. return True
  734. # Check error from fp64 version
  735. if fp64_ref.dtype == torch.float64:
  736. ref_error = rmse(fp64_ref, ref).item()
  737. res_error = rmse(fp64_ref, res).item()
  738. multiplier = 2.0
  739. if (
  740. fp64_ref.numel() < 1000
  741. or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1)
  742. # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE
  743. or tol >= 2 * 1e-2
  744. ):
  745. # In the presence of noise, noise might dominate our error
  746. # metric for smaller tensors.
  747. # Similary, for 1x1 kenerls, there seems to be high noise with amp.
  748. multiplier = 3.0
  749. passes_test = res_error <= (multiplier * ref_error + tol / 10.0)
  750. if not passes_test:
  751. log.error(
  752. f"RMSE (res-fp64): {res_error:.5f}, (ref-fp64): {ref_error:.5f} and shape={res.size()}"
  753. )
  754. # import pdb; pdb.set_trace()
  755. return passes_test
  756. log.error(f"Accuracy failed: allclose not within tol={tol}")
  757. return False
  758. elif isinstance(ref, (str, int, type(None), bool, torch.device)):
  759. r = ref == res
  760. if not r:
  761. log.error(f"Accuracy failed ({type(ref)}): {ref} != {res}")
  762. return r
  763. elif isinstance(ref, float):
  764. r = math.isclose(ref, res, rel_tol=tol, abs_tol=tol)
  765. if not r:
  766. log.error("Accuracy failed (float): {ref} != {res} (within tol={tol})")
  767. return r
  768. elif is_numpy_int_type(ref) or is_numpy_float_type(ref):
  769. if relax_numpy_equality:
  770. ref = ref.item()
  771. r = (type(ref) is type(res)) and (ref == res)
  772. if not r:
  773. log.error("Accuracy failed (numpy): {ref} != {res}")
  774. return r
  775. elif is_numpy_ndarray(ref):
  776. return (type(ref) is type(res)) and (ref == res).all()
  777. elif type(ref).__name__ in (
  778. "MaskedLMOutput",
  779. "Seq2SeqLMOutput",
  780. "CausalLMOutputWithCrossAttentions",
  781. "LongformerMaskedLMOutput",
  782. "Instances",
  783. "SquashedNormal",
  784. "Boxes",
  785. "Normal",
  786. "TanhTransform",
  787. "Foo",
  788. "Variable",
  789. ):
  790. assert type(ref) is type(res)
  791. return all(
  792. same(
  793. getattr(ref, key),
  794. getattr(res, key),
  795. getattr(fp64_ref, key),
  796. cos_similarity=cos_similarity,
  797. tol=tol,
  798. equal_nan=equal_nan,
  799. exact_dtype=exact_dtype,
  800. relax_numpy_equality=relax_numpy_equality,
  801. )
  802. for key in ref.__dict__.keys()
  803. )
  804. else:
  805. raise RuntimeError(f"unsupported type: {type(ref).__name__}")
  806. def format_func_info(code):
  807. short_filename = code.co_filename.split("/")[-1]
  808. return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})"
  809. @contextlib.contextmanager
  810. def disable_cache_limit():
  811. prior = config.cache_size_limit
  812. config.cache_size_limit = sys.maxsize
  813. try:
  814. yield
  815. finally:
  816. pass
  817. config.cache_size_limit = prior
  818. # map from transformed code back to original user code
  819. orig_code_map = ExactWeakKeyDictionary()
  820. # keep a record of code_obj -> list of guard failure reasons for logging
  821. guard_failures = collections.defaultdict(list)
  822. class CompileProfiler:
  823. """Utility for profiling how and what dynamo would compile.
  824. Can be used for
  825. * diagnosing recompilation issues
  826. * determining an appropriate compile cache limit
  827. * (TODO)confirming which functions got compiled/skipped
  828. """
  829. def __init__(self):
  830. self.frame_count = 0
  831. self.op_count = 0
  832. self.backend_ctx_ctor = lambda: disable_cache_limit()
  833. def __call__(self, gm: torch.fx.GraphModule, example_inputs):
  834. self.frame_count += 1
  835. for node in gm.graph.nodes:
  836. if "call" in node.op:
  837. self.op_count += 1
  838. return gm.forward
  839. def get_metrics(self):
  840. return {"guard_failures": guard_failures}
  841. def report(self):
  842. metrics = self.get_metrics()
  843. gf = metrics["guard_failures"]
  844. def num_recompiles(code):
  845. return len(gf[code])
  846. def recompile_reasons(code):
  847. return "\n".join([str(x) for x in gf[code]])
  848. summarized_gf = [
  849. [format_func_info(code), num_recompiles(code), recompile_reasons(code)]
  850. for code in gf
  851. ]
  852. rpt = "Torchdynamo Profiler Report\n"
  853. if "graph_break" in counters:
  854. rpt += "\n"
  855. rpt += "The following conditions caused torchdynamo to break out of tracing and fall back to python.\n"
  856. rpt += (
  857. "You may gain additional insight by passing `nopython=True` to torch._dynamo.optimize, "
  858. "to break on the first condition.\n"
  859. )
  860. graph_breaks = counters["graph_break"]
  861. rpt += tabulate(
  862. [[msg, graph_breaks[msg]] for msg in graph_breaks],
  863. headers=["Graph Break Reason", "Count"],
  864. )
  865. if len(gf):
  866. max_recompiles = max([num_recompiles(code) for code in gf])
  867. rpt += "\n"
  868. rpt += (
  869. "These subgraphs were recompiled more than once due to guard failures."
  870. )
  871. rpt += (
  872. "Guard failures indicate some condition assumed to be static by the tracer changed, "
  873. "making it unsafe to reuse the compiled program."
  874. )
  875. rpt += tabulate(
  876. summarized_gf,
  877. headers=["Function", "Num Recompiles", "Recompile Reasons"],
  878. )
  879. rpt += "\n"
  880. rpt += (
  881. f"Set torch._dynamo.config.cache_size_limit to "
  882. f"{max_recompiles} to avoid being cache limited.\n"
  883. )
  884. else:
  885. rpt += "No cache-limited recompilations detected.\n"
  886. return rpt
  887. # return same dir unless user changes config between calls
  888. @functools.lru_cache(None)
  889. def _get_debug_dir(root_dir):
  890. dir_name = (
  891. "run_"
  892. + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
  893. # use pid to avoid conflicts among ranks
  894. + "-pid_"
  895. + str(os.getpid())
  896. )
  897. return os.path.join(root_dir, dir_name)
  898. def get_debug_dir():
  899. debug_root = config.debug_dir_root
  900. return _get_debug_dir(debug_root)
  901. def get_fake_value(node, tx):
  902. """
  903. Run the computation represented by `node` using fake tensors and return the result.
  904. """
  905. from .exc import TorchRuntimeError, unimplemented, Unsupported
  906. op = node.op
  907. def fake_wrapper(e):
  908. if isinstance(e, torch.Tensor):
  909. assert isinstance(e, FakeTensor)
  910. return e
  911. def visit(n: torch.fx.Node):
  912. return n.meta["example_value"]
  913. args, kwargs = torch.fx.node.map_arg((node.args, node.kwargs), visit)
  914. args = tree_map(fake_wrapper, args)
  915. kwargs = tree_map(fake_wrapper, kwargs)
  916. nnmodule = None
  917. if op == "call_module":
  918. nnmodule = tx.output.nn_modules[node.target]
  919. if not is_lazy_module(nnmodule):
  920. nnmodule = deepcopy_to_fake_tensor(nnmodule, tx.fake_mode)
  921. if op == "call_module" and is_lazy_module(nnmodule):
  922. assert nnmodule is not None
  923. # In the case of a lazy module, we want to run
  924. # the pre-hooks which initialize it
  925. nnmodule(*args, **kwargs)
  926. try:
  927. with tx.fake_mode, enable_python_dispatcher():
  928. return wrap_fake_exception(
  929. lambda: run_node(tx.output, node, args, kwargs, nnmodule)
  930. )
  931. except Unsupported:
  932. raise
  933. except RuntimeError as e:
  934. cause = e
  935. if e.__cause__ is not None:
  936. cause = e.__cause__
  937. if isinstance(
  938. cause, torch._subclasses.fake_tensor.DataDependentOutputException
  939. ):
  940. unimplemented(f"data dependent operator: {cause.func}")
  941. elif isinstance(
  942. cause, torch._subclasses.fake_tensor.DynamicOutputShapeException
  943. ):
  944. unimplemented(f"dynamic shape operator: {cause.func}")
  945. elif isinstance(
  946. cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode
  947. ):
  948. unimplemented("guard on data-dependent symbolic int/float")
  949. raise TorchRuntimeError() from e
  950. def run_node(output_graph, node, args, kwargs, nnmodule):
  951. """
  952. Runs a given node, with the given args and kwargs.
  953. Behavior is dicatated by a node's op.
  954. run_node is useful for extracting real values out of nodes.
  955. See get_real_value for more info on common usage.
  956. Note: The output_graph arg is only used for 'get_attr' ops
  957. Note: The nnmodule arg is only used for 'call_module' ops
  958. Nodes that are not call_function, call_method, call_module, or get_attr will
  959. raise an AssertionError.
  960. """
  961. op = node.op
  962. try:
  963. if op == "call_function":
  964. return node.target(*args, **kwargs)
  965. elif op == "call_method":
  966. return getattr(args[0], node.target)(*args[1:], **kwargs)
  967. elif op == "call_module":
  968. assert nnmodule is not None
  969. return nnmodule(*args, **kwargs)
  970. elif op == "get_attr":
  971. return output_graph.get_submodule(node.target)
  972. elif op == "placeholder":
  973. assert "example_value" in node.meta
  974. return node.meta["example_value"]
  975. except Exception as e:
  976. raise RuntimeError(
  977. f"Failed running {op} {node.target}(*{args}, **{kwargs}):\n{e}\n(scroll up for backtrace)"
  978. ) from e
  979. raise AssertionError(op)
  980. def get_real_value(node, output_graph):
  981. """
  982. Run the actual computation represented by `node` and return the result.
  983. This will execute any dependent nodes in the graph as well.
  984. """
  985. cache = output_graph.real_value_cache
  986. if node in cache:
  987. return cache[node]
  988. op = node.op
  989. args, kwargs = torch.fx.node.map_arg(
  990. (node.args, node.kwargs),
  991. lambda n: get_real_value(n, output_graph),
  992. )
  993. if op == "call_module":
  994. nn_module = output_graph.nn_modules[node.target]
  995. if not is_lazy_module(nn_module):
  996. nn_module = copy.deepcopy(nn_module)
  997. else:
  998. # In the case of a lazy module, we want to run
  999. # the pre-hooks which initialize it
  1000. nn_module(*args, **kwargs)
  1001. else:
  1002. nn_module = None
  1003. try:
  1004. real_value = run_node(output_graph, node, args, kwargs, nn_module)
  1005. cache[node] = real_value
  1006. except RuntimeError as e:
  1007. raise TorchRuntimeError() from e
  1008. return real_value
  1009. def assert_no_fake_params_or_buffers(gm):
  1010. from torch._subclasses.fake_tensor import FakeTensorConfig
  1011. def stack_or_hint(t):
  1012. if FakeTensorConfig.debug:
  1013. import traceback
  1014. return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}"
  1015. else:
  1016. return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors."
  1017. for name, buffer in gm.named_buffers():
  1018. assert not isinstance(
  1019. buffer, torch._subclasses.FakeTensor
  1020. ), f"Unexpected fake buffer {name} {stack_or_hint(buffer)}"
  1021. for name, param in gm.named_parameters():
  1022. assert not isinstance(
  1023. param, torch._subclasses.FakeTensor
  1024. ), f"Unexpected fake param {name} {stack_or_hint(param)}"
  1025. def fake_mode_from_tensors(inputs: List[Any]):
  1026. """
  1027. Takes a list of anything, unflattened is fine, returns a fake_mode
  1028. if any are fake. All fake modes on all fake tensors must be identical.
  1029. Returns None if no fake_mode is fine
  1030. """
  1031. flat_inputs, _ = tree_flatten(inputs)
  1032. fake_mode = None
  1033. for flat_input in flat_inputs:
  1034. if isinstance(flat_input, torch._subclasses.FakeTensor):
  1035. if fake_mode is None:
  1036. fake_mode = flat_input.fake_mode
  1037. else:
  1038. assert fake_mode is flat_input.fake_mode
  1039. return fake_mode
  1040. def fqn(obj: Any):
  1041. """
  1042. Returns the fully qualified name of the object.
  1043. """
  1044. return f"{obj.__module__}.{obj.__qualname__}"
  1045. def ifdyn(count1, count2):
  1046. if torch._dynamo.config.dynamic_shapes:
  1047. return count1
  1048. else:
  1049. return count2
  1050. def import_submodule(mod: types.ModuleType):
  1051. """
  1052. Ensure all the files in a given submodule are imported
  1053. """
  1054. for filename in sorted(os.listdir(os.path.dirname(mod.__file__))):
  1055. if filename.endswith(".py") and filename[0] != "_":
  1056. importlib.import_module(f"{mod.__name__}.{filename[:-3]}")