gradcheck.py 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import functools
  4. import warnings
  5. from collections.abc import Callable, Iterable
  6. from itertools import product
  7. from typing import Optional, Union
  8. from typing_extensions import deprecated
  9. import torch
  10. import torch.testing
  11. # pyrefly: ignore [deprecated]
  12. from torch._vmap_internals import _vmap, vmap
  13. from torch.overrides import is_tensor_like
  14. from torch.types import _TensorOrOptionalTensors, _TensorOrTensors
  15. # Note: `get_*_jacobian` functions are added here even though we didn't intend to make them public
  16. # since they have been exposed from before we added `__all__` and we already maintain BC for them
  17. # We should eventually deprecate them and remove them from `__all__`
  18. __all__ = [
  19. "gradcheck",
  20. "gradgradcheck",
  21. "GradcheckError",
  22. "get_numerical_jacobian",
  23. "get_analytical_jacobian",
  24. "get_numerical_jacobian_wrt_specific_input",
  25. ]
  26. class GradcheckError(RuntimeError):
  27. r"""Error raised by :func:`gradcheck` and :func:`gradgradcheck`."""
  28. def _is_sparse_compressed_tensor(obj: torch.Tensor):
  29. return obj.layout in {
  30. torch.sparse_csr,
  31. torch.sparse_csc,
  32. torch.sparse_bsr,
  33. torch.sparse_bsc,
  34. }
  35. def _is_sparse_any_tensor(obj: torch.Tensor):
  36. return _is_sparse_compressed_tensor(obj) or obj.layout is torch.sparse_coo
  37. def _is_float_or_complex_tensor(obj):
  38. return is_tensor_like(obj) and (obj.is_floating_point() or obj.is_complex())
  39. def _allocate_jacobians_with_inputs(
  40. input_tensors: tuple, numel_output
  41. ) -> tuple[torch.Tensor, ...]:
  42. # Makes zero-filled tensors from inputs. If `numel_output` is not None, for
  43. # each tensor in `input_tensors`, returns a new zero-filled tensor with height
  44. # of `t.numel` and width of `numel_output`. Otherwise, for each tensor, returns
  45. # a 1-d tensor with size `(t.numel,)`. Each new tensor will be strided and have
  46. # the same dtype and device as those of the corresponding input.
  47. out: list[torch.Tensor] = [
  48. t.new_zeros((t.numel(), numel_output), layout=torch.strided)
  49. for t in input_tensors
  50. if _is_float_or_complex_tensor(t) and t.requires_grad
  51. ]
  52. return tuple(out)
  53. def _allocate_jacobians_with_outputs(
  54. output_tensors: tuple, numel_input, dtype=None, device=None
  55. ) -> tuple[torch.Tensor, ...]:
  56. # Makes zero-filled tensors from outputs. If `dim` is not None, for each tensor
  57. # in `output_tensors`, returns a new zero-filled tensor with height of `dim` and
  58. # width of `t.numel`. Otherwise, for each tensor, returns a 1-d tensor with size
  59. # (t.numel,).
  60. options = {"dtype": dtype, "device": device, "layout": torch.strided}
  61. out: list[torch.Tensor] = [
  62. t.new_zeros((numel_input, t.numel()), **options)
  63. for t in output_tensors
  64. if _is_float_or_complex_tensor(t)
  65. ]
  66. return tuple(out)
  67. def _iter_tensors(
  68. x: Union[torch.Tensor, Iterable[torch.Tensor]], only_requiring_grad: bool = False
  69. ) -> Iterable[torch.Tensor]:
  70. if is_tensor_like(x):
  71. # mypy doesn't narrow type of `x` to torch.Tensor
  72. if x.requires_grad or not only_requiring_grad: # type: ignore[union-attr]
  73. yield x # type: ignore[misc]
  74. elif isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
  75. for elem in x:
  76. yield from _iter_tensors(elem, only_requiring_grad)
  77. def _densify(x):
  78. # return a copy of sparse x with all unspecified elements
  79. # "replaced" with zero-valued elements
  80. if isinstance(x, (list, tuple)):
  81. return type(x)(map(_densify, x))
  82. elif not is_tensor_like(x) or x.layout in {torch.strided, torch._mkldnn}: # type: ignore[attr-defined] # no attr _mkldnn
  83. return x
  84. elif x.layout is torch.sparse_coo:
  85. device = x.device
  86. indices_dtype = x._indices().dtype
  87. tmp = torch.ones(x.shape[: x.sparse_dim()], dtype=torch.int8, device=device)
  88. indices = tmp.nonzero().t().to(dtype=indices_dtype)
  89. values = torch.zeros(
  90. (tmp.numel(), *x.shape[x.sparse_dim() :]), dtype=x.dtype, device=device
  91. )
  92. x_coalesced = x.detach().coalesce()
  93. if x_coalesced.numel() > 0:
  94. stride = tmp.stride()
  95. flat_indices = (
  96. x_coalesced.indices()
  97. .mul(
  98. torch.tensor(stride, dtype=indices_dtype, device=device).unsqueeze(
  99. 1
  100. )
  101. )
  102. .sum(0)
  103. )
  104. values[flat_indices] = x_coalesced.values()
  105. return (
  106. torch.sparse_coo_tensor(indices, values, x.shape)
  107. ._coalesced_(True)
  108. .requires_grad_(x.requires_grad)
  109. )
  110. elif _is_sparse_compressed_tensor(x):
  111. blocksize = (
  112. x.values().shape[1:3]
  113. if x.layout in {torch.sparse_bsr, torch.sparse_bsc}
  114. else None
  115. )
  116. compressed_indices = (
  117. x.crow_indices()
  118. if x.layout in {torch.sparse_csr, torch.sparse_bsr}
  119. else x.ccol_indices()
  120. )
  121. # We'll use intermediate sparse COO for simplicity
  122. r = _densify(x.detach().to_sparse(layout=torch.sparse_coo)).to_sparse(
  123. layout=x.layout, blocksize=blocksize
  124. )
  125. # Check that all elements are specified also after `to_sparse` op:
  126. dense_numel = r.values().numel() // max(1, r.values().shape[0])
  127. batch_numel = compressed_indices.numel() // compressed_indices.shape[-1]
  128. sparse_numel = r.numel() // max(1, dense_numel * batch_numel)
  129. if sparse_numel != r._nnz():
  130. raise AssertionError(
  131. f"{x.layout} densify failed: expected nnz={sparse_numel} but got {r._nnz()}"
  132. )
  133. return r.requires_grad_(x.requires_grad)
  134. elif _is_sparse_any_tensor(x):
  135. raise NotImplementedError(x.layout)
  136. return x
  137. def _iter_tensor(x_tensor):
  138. # (Only used for slow gradcheck) Returns a generator that yields the following
  139. # elements at each iteration:
  140. # 1) a tensor: the same tensor is returned across all iterations. The tensor
  141. # is not the same as the original x_tensor as given as input - it is
  142. # prepared so that it can be modified in-place. Depending on whether the
  143. # input tensor is strided, sparse, or dense, the returned tensor may or may
  144. # not share storage with x_tensor.
  145. # 2) a tuple of indices that can be used with advanced indexing (yielded in
  146. # dictionary order)
  147. # 3) flattened index that will be used to index into the Jacobian tensor
  148. #
  149. # For a tensor t with size (2, 2), _iter_tensor yields:
  150. # `x, (0, 0), 0`, `x, (0, 1), 1`, `x, (1, 0), 2`, `x, (1, 1), 3`
  151. #
  152. # where x is the t.data of the original tensor. Perturbing the entry of x
  153. # at index (1, 1) yields the 3rd column of the overall Jacobian matrix.
  154. if _is_sparse_any_tensor(x_tensor):
  155. def get_stride(size):
  156. dim = len(size)
  157. tmp = 1
  158. stride = [0] * dim
  159. for i in reversed(range(dim)):
  160. stride[i] = tmp
  161. tmp *= size[i]
  162. return stride
  163. x_nnz = x_tensor._nnz()
  164. x_size = list(x_tensor.size())
  165. if x_tensor.layout is torch.sparse_coo:
  166. x_indices = x_tensor._indices().t()
  167. x_values = x_tensor._values()
  168. elif x_tensor.layout is torch.sparse_csr:
  169. x_indices = torch._convert_indices_from_csr_to_coo(
  170. x_tensor.crow_indices(), x_tensor.col_indices()
  171. ).t()
  172. x_values = x_tensor.values()
  173. elif x_tensor.layout is torch.sparse_csc:
  174. x_indices = torch._convert_indices_from_csr_to_coo(
  175. x_tensor.ccol_indices(), x_tensor.row_indices(), transpose=True
  176. ).t()
  177. x_values = x_tensor.values()
  178. elif x_tensor.layout is torch.sparse_bsr:
  179. x_block_values = x_tensor.values()
  180. x_blocksize = x_block_values.size()[1:3]
  181. x_indices = (
  182. torch._convert_indices_from_csr_to_coo(
  183. x_tensor.crow_indices(), x_tensor.col_indices()
  184. )
  185. .repeat_interleave(x_blocksize[0] * x_blocksize[1], 1)
  186. .mul_(torch.tensor(x_blocksize, device=x_tensor.device).reshape(2, 1))
  187. .add_(
  188. torch.stack(
  189. torch.where(torch.ones(x_blocksize, device=x_tensor.device))
  190. ).repeat(1, x_nnz)
  191. )
  192. .t()
  193. )
  194. x_values = x_block_values.flatten(0, 2)
  195. x_nnz = x_values.size(0)
  196. elif x_tensor.layout is torch.sparse_bsc:
  197. x_block_values = x_tensor.values()
  198. x_blocksize = x_block_values.size()[1:3]
  199. x_indices = (
  200. torch._convert_indices_from_csr_to_coo(
  201. x_tensor.ccol_indices(), x_tensor.row_indices(), transpose=True
  202. )
  203. .repeat_interleave(x_blocksize[0] * x_blocksize[1], 1)
  204. .mul_(torch.tensor(x_blocksize, device=x_tensor.device).reshape(2, 1))
  205. .add_(
  206. torch.stack(
  207. torch.where(torch.ones(x_blocksize, device=x_tensor.device))
  208. ).repeat(1, x_nnz)
  209. )
  210. .t()
  211. )
  212. x_values = x_block_values.flatten(0, 2)
  213. x_nnz = x_values.size(0)
  214. else:
  215. raise NotImplementedError(f"_iter_tensor for {x_tensor.layout} input")
  216. x_stride = get_stride(x_size)
  217. # Use .data here to get around the version check
  218. x_values = x_values.data
  219. for i in range(x_nnz):
  220. x_value = x_values[i]
  221. for x_idx in product(*[range(m) for m in x_values.size()[1:]]):
  222. indices = x_indices[i].tolist() + list(x_idx)
  223. d_idx = sum(indices[k] * x_stride[k] for k in range(len(x_size)))
  224. yield x_value, x_idx, d_idx
  225. elif x_tensor.layout == torch._mkldnn: # type: ignore[attr-defined]
  226. for d_idx, x_idx in enumerate(product(*[range(m) for m in x_tensor.size()])):
  227. # this is really inefficient, but without indexing implemented, there's
  228. # not really a better way than converting back and forth
  229. x_tensor_dense = x_tensor.to_dense()
  230. yield x_tensor_dense, x_idx, d_idx
  231. else:
  232. # Use .data here to get around the version check
  233. x_tensor = x_tensor.data
  234. for d_idx, x_idx in enumerate(product(*[range(m) for m in x_tensor.size()])):
  235. yield x_tensor, x_idx, d_idx
  236. def _get_numerical_jacobian(
  237. fn, inputs, outputs=None, target=None, eps=1e-3, is_forward_ad=False
  238. ) -> list[tuple[torch.Tensor, ...]]:
  239. """Compute the numerical Jacobian of `fn(inputs)` with respect to `target`.
  240. If not specified, targets are the input. Returns M * N Jacobians where N is the
  241. number of tensors in target that require grad and M is the number of non-integral
  242. outputs.
  243. Args:
  244. fn: the function to compute the jacobian for
  245. inputs: inputs to `fn`
  246. outputs: provide precomputed outputs to avoid one extra invocation of fn
  247. target: the Tensors wrt whom Jacobians are calculated (default=`inputs`)
  248. eps: the magnitude of the perturbation during finite differencing
  249. (default=`1e-3`)
  250. is_forward_ad: if this numerical jacobian is computed to be checked wrt
  251. forward AD gradients (this is used for error checking only)
  252. Returns:
  253. A list of M N-tuples of tensors
  254. Note that `target` may not even be part of `input` to `fn`, so please be
  255. **very careful** in this to not clone `target`.
  256. """
  257. jacobians: list[tuple[torch.Tensor, ...]] = []
  258. if outputs is None:
  259. outputs = _as_tuple(fn(*_as_tuple(inputs)))
  260. if not is_forward_ad and any(o.is_complex() for o in outputs):
  261. raise ValueError(
  262. "Expected output to be non-complex. get_numerical_jacobian no "
  263. "longer supports functions that return complex outputs."
  264. )
  265. if target is None:
  266. target = inputs
  267. inp_indices = [
  268. i for i, a in enumerate(target) if is_tensor_like(a) and a.requires_grad
  269. ]
  270. for inp, inp_idx in zip(_iter_tensors(target, True), inp_indices):
  271. jacobians += [
  272. get_numerical_jacobian_wrt_specific_input(
  273. fn,
  274. inp_idx,
  275. inputs,
  276. outputs,
  277. eps,
  278. input=inp,
  279. is_forward_ad=is_forward_ad,
  280. )
  281. ]
  282. return jacobians
  283. @deprecated(
  284. "`get_numerical_jacobian` was part of PyTorch's private API and not "
  285. "meant to be exposed. We are deprecating it and it will be removed "
  286. "in a future version of PyTorch. If you have a specific use for "
  287. "this or feature request for this to be a stable API, please file "
  288. "us an issue at https://github.com/pytorch/pytorch/issues/new",
  289. category=FutureWarning,
  290. )
  291. def get_numerical_jacobian(fn, inputs, target=None, eps=1e-3, grad_out=1.0):
  292. """Compute the numerical Jacobian for a given fn and its inputs.
  293. This is a Deprecated API.
  294. Args:
  295. fn: the function to compute the Jacobian for (must take inputs as a tuple)
  296. inputs: input to `fn`
  297. target: the Tensors wrt whom Jacobians are calculated (default=`input`)
  298. eps: the magnitude of the perturbation during finite differencing
  299. (default=`1e-3`)
  300. grad_out: defaults to 1.0.
  301. Returns:
  302. A list of Jacobians of `fn` (restricted to its first output) with respect to
  303. each input or target, if provided.
  304. Note that `target` may not even be part of `input` to `fn`, so please be
  305. **very careful** in this to not clone `target`.
  306. """
  307. if (
  308. grad_out != 1.0
  309. ): # grad_out param is only kept for backward compatibility reasons
  310. raise ValueError(
  311. "Expected grad_out to be 1.0. get_numerical_jacobian no longer "
  312. "supports values of grad_out != 1.0."
  313. )
  314. def fn_pack_inps(*inps):
  315. return fn(inps)
  316. jacobians = _get_numerical_jacobian(fn_pack_inps, inputs, None, target, eps)
  317. return tuple(jacobian_for_each_output[0] for jacobian_for_each_output in jacobians)
  318. def _compute_numerical_gradient(fn, entry, v, norm_v, nbhd_checks_fn):
  319. # Computes numerical directional derivative as finite difference
  320. # of function `fn` at input `entry`, perturbed by vector `v`.
  321. if _is_sparse_compressed_tensor(entry):
  322. # sparse compressed tensors don't implement sub/add/copy_
  323. # yet. However, in non-masked semantics context entry and v
  324. # have the same sparse indices ...
  325. if entry.layout != v.layout:
  326. raise AssertionError(
  327. f"Expected entry and v to have the same layout, but got {entry.layout} and {v.layout}"
  328. )
  329. if entry._nnz() != v._nnz():
  330. raise AssertionError(
  331. f"Expected entry and v to have the same nnz, but got {entry._nnz()} and {v._nnz()} "
  332. f"with entry shape {entry.shape}"
  333. )
  334. # ... the finite differencing can be performed on values only:
  335. entry = entry.values()
  336. v = v.values()
  337. # we'll detach to avoid backward computations that sparse
  338. # tensors have limited support for.
  339. entry = entry.detach()
  340. orig = entry.clone()
  341. entry.copy_(orig - v)
  342. outa = fn()
  343. entry.copy_(orig + v)
  344. outb = fn()
  345. entry.copy_(orig)
  346. def compute(a, b):
  347. nbhd_checks_fn(a, b)
  348. ret = (b - a) / (2 * norm_v) # use central difference approx
  349. return ret.detach().reshape(-1)
  350. return tuple(compute(a, b) for (a, b) in zip(outa, outb))
  351. def _compute_numerical_jvps_wrt_specific_input(
  352. jvp_fn, delta, input_is_complex, is_forward_ad=False
  353. ) -> list[torch.Tensor]:
  354. # Computing the jacobian only works for real delta
  355. # For details on the algorithm used here, refer:
  356. # Section 3.5.3 https://arxiv.org/pdf/1701.00392.pdf
  357. # s = fn(z) where z = x for real valued input
  358. # and z = x + yj for complex valued input
  359. jvps: list[torch.Tensor] = []
  360. ds_dx_tup = jvp_fn(delta[0] if isinstance(delta, tuple) else delta)
  361. if input_is_complex: # C -> R
  362. ds_dy_tup = (
  363. jvp_fn(delta[1] * 1j) if isinstance(delta, tuple) else jvp_fn(delta * 1j)
  364. )
  365. for ds_dx, ds_dy in zip(ds_dx_tup, ds_dy_tup):
  366. if ds_dx.is_complex():
  367. raise AssertionError("Expected ds_dx to be real-valued, not complex")
  368. # conjugate wirtinger derivative
  369. conj_w_d = ds_dx + ds_dy * 1j
  370. jvps.append(conj_w_d)
  371. else:
  372. for ds_dx in ds_dx_tup: # R -> R or (R -> C for the forward AD case)
  373. if not is_forward_ad and ds_dx.is_complex():
  374. raise AssertionError("Expected ds_dx to be real-valued, not complex.")
  375. jvps.append(ds_dx)
  376. return jvps
  377. def _combine_jacobian_cols(
  378. jacobians_cols: dict[int, list[torch.Tensor]], outputs, input, numel
  379. ) -> tuple[torch.Tensor, ...]:
  380. # jacobian_cols maps column_idx -> output_idx -> single column of jacobian Tensor
  381. # we return a list that maps output_idx -> full jacobian Tensor
  382. jacobians = _allocate_jacobians_with_outputs(
  383. outputs, numel, dtype=input.dtype if input.dtype.is_complex else None
  384. )
  385. for i, jacobian in enumerate(jacobians):
  386. for k, v in jacobians_cols.items():
  387. jacobian[k] = v[i]
  388. return jacobians
  389. def _prepare_input(
  390. input: torch.Tensor, maybe_perturbed_input: Optional[torch.Tensor], fast_mode=False
  391. ) -> torch.Tensor:
  392. # Prepares the inputs to be passed into the function while including the new
  393. # modified input.
  394. if input.layout == torch._mkldnn: # type: ignore[attr-defined] # no attr _mkldnn
  395. # Convert back to mkldnn
  396. if maybe_perturbed_input is not None:
  397. return maybe_perturbed_input.to_mkldnn()
  398. else:
  399. return input
  400. elif _is_sparse_any_tensor(input):
  401. if fast_mode and maybe_perturbed_input is not None:
  402. # entry is already a "cloned" version of the original tensor
  403. # thus changes to entry are not reflected in the input
  404. return maybe_perturbed_input
  405. else:
  406. return input
  407. else:
  408. # We cannot use entry (input.data) if we want gradgrad to work because
  409. # fn (in the gradgrad case) needs to compute grad wrt input
  410. return input
  411. def _check_outputs_same_dtype_and_shape(output1, output2, eps, idx=None) -> None:
  412. # Check that the returned outputs don't have different dtype or shape when you
  413. # perturb the input
  414. on_index = f"on index {idx} " if idx is not None else ""
  415. if output1.shape != output2.shape:
  416. raise AssertionError(
  417. f"Expected `func` to return outputs with the same shape"
  418. f" when inputs are perturbed {on_index}by {eps}, but got:"
  419. f" shapes {output1.shape} and {output2.shape}."
  420. )
  421. if output1.dtype != output2.dtype:
  422. raise AssertionError(
  423. f"Expected `func` to return outputs with the same dtype"
  424. f" when inputs are perturbed {on_index}by {eps}, but got:"
  425. f" dtypes {output1.dtype} and {output2.dtype}."
  426. )
  427. def get_numerical_jacobian_wrt_specific_input(
  428. fn, input_idx, inputs, outputs, eps, input=None, is_forward_ad=False
  429. ) -> tuple[torch.Tensor, ...]:
  430. # Computes the numerical jacobians wrt to a single input. Returns N jacobian
  431. # tensors, where N is the number of outputs. We use a dictionary for
  432. # jacobian_cols because indices aren't necessarily consecutive for sparse inputs
  433. # When we perturb only a single element of the input tensor at a time, the jvp
  434. # is equivalent to a single col of the Jacobian matrix of fn.
  435. jacobian_cols: dict[int, list[torch.Tensor]] = {}
  436. input = inputs[input_idx] if input is None else input
  437. if not input.requires_grad:
  438. raise AssertionError("Expected input to have requires_grad=True")
  439. for x, idx, d_idx in _iter_tensor(input):
  440. wrapped_fn = _with_prepare_inputs(fn, inputs, input_idx, x)
  441. input_to_perturb = x[idx]
  442. nbhd_checks_fn = functools.partial(
  443. _check_outputs_same_dtype_and_shape, idx=idx, eps=eps
  444. )
  445. jvp_fn = _get_numerical_jvp_fn(
  446. wrapped_fn, input_to_perturb, eps, nbhd_checks_fn
  447. )
  448. jacobian_cols[d_idx] = _compute_numerical_jvps_wrt_specific_input(
  449. jvp_fn, eps, x.is_complex(), is_forward_ad
  450. )
  451. return _combine_jacobian_cols(jacobian_cols, outputs, input, input.numel())
  452. def _get_analytical_jacobian_forward_ad(
  453. fn, inputs, outputs, *, check_grad_dtypes=False, all_u=None
  454. ) -> tuple[tuple[torch.Tensor, ...], ...]:
  455. """Compute the analytical Jacobian using forward mode AD of `fn(inputs)` using forward mode AD with respect to `target`.
  456. Return N * M Jacobians where N is the number of tensors in target that require grad and
  457. M is the number of non-integral outputs.
  458. Contrary to other functions here, this function requires "inputs" to actually be used by the function.
  459. The computed value is expected to be wrong if the function captures the inputs by side effect instead of
  460. using the passed ones (many torch.nn tests do this).
  461. Args:
  462. fn: the function to compute the jacobian for
  463. inputs: inputs to `fn`
  464. outputs: provide precomputed outputs to avoid one extra invocation of fn
  465. check_grad_dtypes: if True, will check that the gradient dtype are valid
  466. all_u (optional): if provided, the Jacobian will be right multiplied with this vector
  467. Returns:
  468. A tuple of M N-tuples of tensors
  469. """
  470. # To avoid early import issues
  471. fwAD = torch.autograd.forward_ad
  472. tensor_inputs = tuple(i for i in inputs if is_tensor_like(i) and i.requires_grad)
  473. if any(i.is_complex() for i in tensor_inputs):
  474. raise ValueError(
  475. "Expected inputs to be non-complex for _get_analytical_jacobian_forward_ad."
  476. )
  477. if all_u:
  478. jacobians = tuple(
  479. _allocate_jacobians_with_outputs(outputs, 1) for i in tensor_inputs
  480. )
  481. else:
  482. jacobians = tuple(
  483. _allocate_jacobians_with_outputs(outputs, i.numel()) for i in tensor_inputs
  484. )
  485. with fwAD.dual_level():
  486. fw_grads = []
  487. dual_inputs = []
  488. for inp in inputs:
  489. if is_tensor_like(inp) and inp.requires_grad:
  490. if inp.layout == torch._mkldnn: # type: ignore[attr-defined]
  491. raise ValueError(
  492. "MKLDNN inputs are not support for forward AD gradcheck."
  493. )
  494. inp = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  495. # If inp is a differentiable view, the dual might not be the tangent given to
  496. # make_dual, so read it explicitly from the dual tensor
  497. fw_grads.append(fwAD.unpack_dual(inp)[1])
  498. dual_inputs.append(inp)
  499. if all_u:
  500. # Do the full reduction in one pass
  501. # To be consistent with numerical evaluation, we actually compute one reduction per input
  502. for i, (fw_grad, u) in enumerate(zip(fw_grads, all_u)):
  503. fw_grad.copy_(u.view_as(fw_grad))
  504. raw_outputs = _as_tuple(fn(*dual_inputs))
  505. dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs)
  506. for index_o, d_o in enumerate(dual_outputs):
  507. val, res = fwAD.unpack_dual(d_o)
  508. if (
  509. check_grad_dtypes
  510. and res is not None
  511. and val.is_complex() != res.is_complex()
  512. ):
  513. raise GradcheckError("Forward AD gradient has dtype mismatch.")
  514. # Remove extra dimension of size 1 corresponding to the reduced input
  515. jacobians[i][index_o].squeeze_(0)
  516. if res is None:
  517. jacobians[i][index_o].zero_()
  518. else:
  519. jacobians[i][index_o].copy_(res.reshape(-1))
  520. fw_grad.zero_()
  521. else:
  522. # Reconstruct the full Jacobian column by column
  523. for i, fw_grad in enumerate(fw_grads):
  524. for lin_idx, grad_idx in enumerate(
  525. product(*[range(m) for m in fw_grad.size()])
  526. ):
  527. fw_grad[grad_idx] = 1.0
  528. raw_outputs = _as_tuple(fn(*dual_inputs))
  529. dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs)
  530. for index_o, d_o in enumerate(dual_outputs):
  531. val, res = fwAD.unpack_dual(d_o)
  532. if (
  533. check_grad_dtypes
  534. and res is not None
  535. and val.is_complex() != res.is_complex()
  536. ):
  537. raise GradcheckError(
  538. "Forward AD gradient has dtype mismatch."
  539. )
  540. if res is None:
  541. jacobians[i][index_o][lin_idx].zero_()
  542. else:
  543. jacobians[i][index_o][lin_idx].copy_(res.reshape(-1))
  544. fw_grad[grad_idx] = 0.0
  545. return jacobians
  546. def _get_input_to_perturb(input):
  547. # Prepare the input so that it can be modified in-place and do certain
  548. # operations that require the tensor to have strides. If fast_mode=False,
  549. # _iter_tensor would handle the below cases:
  550. if input.layout == torch._mkldnn: # type: ignore[attr-defined] # no attr _mkldnn
  551. # Convert to dense so we can perform operations that require strided tensors
  552. input_to_perturb = input.to_dense()
  553. elif _is_sparse_any_tensor(input):
  554. # Clone because input may require grad, and copy_ calls resize_,
  555. # which is not allowed for .data
  556. input_to_perturb = input.clone()
  557. else:
  558. input_to_perturb = input.data
  559. return input_to_perturb
  560. def _with_prepare_inputs(fn, inputs, input_idx, input_to_perturb, fast_mode=False):
  561. # Wraps `fn` so that its inputs are already supplied
  562. def wrapped_fn():
  563. inp = tuple(
  564. _prepare_input(a, input_to_perturb if i == input_idx else None, fast_mode)
  565. if is_tensor_like(a)
  566. else a
  567. for i, a in enumerate(_as_tuple(inputs))
  568. )
  569. return tuple(a.clone() for a in _as_tuple(fn(*inp)))
  570. return wrapped_fn
  571. def _get_numerical_jvp_fn(wrapped_fn, input_to_perturb, eps, nbhd_checks_fn):
  572. # Wraps jvp_fn so that certain arguments are already supplied
  573. def jvp_fn(delta):
  574. return _compute_numerical_gradient(
  575. wrapped_fn, input_to_perturb, delta, eps, nbhd_checks_fn
  576. )
  577. return jvp_fn
  578. def _reshape_tensor_or_tuple(u, shape):
  579. # We don't need to reshape when input corresponding to u is sparse
  580. if isinstance(u, tuple):
  581. if not _is_sparse_any_tensor(u[0]):
  582. return (u[0].reshape(shape), u[1].reshape(shape))
  583. else:
  584. if not _is_sparse_any_tensor(u):
  585. return u.reshape(shape)
  586. return u
  587. def _mul_tensor_or_tuple(u, k):
  588. if isinstance(u, tuple):
  589. return (k * u[0], k * u[1])
  590. else:
  591. return k * u
  592. def _get_numerical_jvp_wrt_specific_input(
  593. fn, input_idx, inputs, u, eps, is_forward_ad=False
  594. ) -> list[torch.Tensor]:
  595. input = inputs[input_idx]
  596. input_to_perturb = _get_input_to_perturb(input)
  597. wrapped_fn = _with_prepare_inputs(fn, inputs, input_idx, input_to_perturb, True)
  598. nbhd_checks_fn = functools.partial(_check_outputs_same_dtype_and_shape, eps=eps)
  599. jvp_fn = _get_numerical_jvp_fn(wrapped_fn, input_to_perturb, eps, nbhd_checks_fn)
  600. u = _reshape_tensor_or_tuple(u, input_to_perturb.shape)
  601. u = _mul_tensor_or_tuple(u, eps)
  602. return _compute_numerical_jvps_wrt_specific_input(
  603. jvp_fn, u, input.is_complex(), is_forward_ad
  604. )
  605. def _get_numerical_vJu(
  606. fn, inputs, inp_indices, func_out, all_u, all_v, eps, is_forward_ad
  607. ):
  608. # Note that all_v can also be None, in that case, this function only computes Ju.
  609. reduced_jacobians: list[list[torch.Tensor]] = []
  610. for inp_idx, u in zip(inp_indices, all_u):
  611. all_Ju = _get_numerical_jvp_wrt_specific_input(
  612. fn, inp_idx, inputs, u, eps, is_forward_ad
  613. )
  614. # Filter out the Ju for non floating point outputs
  615. filtered_Ju = []
  616. func_out = _as_tuple(func_out)
  617. if len(all_Ju) != len(func_out):
  618. raise AssertionError(
  619. f"Expected all_Ju and func_out to have the same length, "
  620. f"but got {len(all_Ju)} and {len(func_out)}"
  621. )
  622. for Ju, output in zip(all_Ju, func_out):
  623. if _is_float_or_complex_tensor(output):
  624. filtered_Ju.append(Ju)
  625. else:
  626. # TODO: handle the other Ju
  627. pass
  628. if all_v is not None:
  629. jacobian_scalars: list[torch.Tensor] = []
  630. for v, Ju in zip(all_v, filtered_Ju):
  631. jacobian_scalars.append(_dot_with_type_promotion(v, Ju))
  632. reduced_jacobians.append(jacobian_scalars)
  633. else:
  634. reduced_jacobians.append(filtered_Ju)
  635. return reduced_jacobians
  636. def _check_jacobians_equal(j1, j2, atol):
  637. # Check whether the max difference between two Jacobian tensors are within some
  638. # tolerance `atol`.
  639. for j1_x, j2_x in zip(j1, j2):
  640. if j1_x.numel() != 0 and (j1_x - j2_x).abs().max() > atol:
  641. return False
  642. return True
  643. def _stack_and_check_tensors(
  644. list_of_list_of_tensors, inputs, numel_outputs
  645. ) -> tuple[tuple[torch.Tensor, ...], bool, bool]:
  646. # For the ith tensor in the inner list checks whether it has the same size and
  647. # dtype as the ith differentiable input.
  648. out_jacobians = _allocate_jacobians_with_inputs(inputs, numel_outputs)
  649. diff_input_list = list(_iter_tensors(inputs, True))
  650. correct_grad_sizes = True
  651. correct_grad_types = True
  652. for i, tensor_list in enumerate(list_of_list_of_tensors):
  653. inp = diff_input_list[i]
  654. out_jacobian = out_jacobians[i]
  655. for j, tensor in enumerate(tensor_list):
  656. if tensor is not None and tensor.size() != inp.size():
  657. correct_grad_sizes = False
  658. elif tensor is not None and tensor.dtype != inp.dtype:
  659. correct_grad_types = False
  660. if tensor is None:
  661. out_jacobian[:, j].zero_()
  662. else:
  663. dense = tensor.to_dense() if tensor.layout != torch.strided else tensor
  664. if out_jacobian[:, j].numel() != dense.numel():
  665. raise AssertionError(
  666. f"Expected out_jacobian column to have {dense.numel()} elements, "
  667. f"but got {out_jacobian[:, j].numel()}"
  668. )
  669. out_jacobian[:, j] = dense.reshape(-1)
  670. return out_jacobians, correct_grad_sizes, correct_grad_types
  671. FAILED_NONDET_MSG = """\n
  672. NOTE: If your op relies on non-deterministic operations i.e., it is listed here:
  673. https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html
  674. this failure might be expected.
  675. If you are adding a new operator, please file an issue and then use one of the
  676. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  677. If the test
  678. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  679. with `nondet_tol=<tol>` as a keyword argument.
  680. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  681. to have `gradcheck_nondet_tol=<tol>`.
  682. - is a Module test (e.g., in common_nn.py), then modify the corresponding
  683. module_test entry to have `gradcheck_nondet_tol=<tol>`
  684. """
  685. def _check_analytical_jacobian_attributes(
  686. inputs, output, nondet_tol, check_grad_dtypes, fast_mode=False, v=None
  687. ) -> tuple[torch.Tensor, ...]:
  688. # This is used by both fast and slow mode:
  689. # - For slow mode, vjps[i][j] is the jth row of the Jacobian wrt the ith
  690. # input.
  691. # - For fast mode, vjps[i][0] is a linear combination of the rows
  692. # of the Jacobian wrt the ith input
  693. diff_input_list = list(_iter_tensors(inputs, True))
  694. def vjp_fn(grad_output):
  695. return torch.autograd.grad(
  696. output, diff_input_list, grad_output, retain_graph=True, allow_unused=True
  697. )
  698. # Compute everything twice to check for nondeterminism (which we call reentrancy)
  699. if fast_mode:
  700. vjps1 = _get_analytical_vjps_wrt_specific_output(vjp_fn, output.clone(), v)
  701. vjps2 = _get_analytical_vjps_wrt_specific_output(vjp_fn, output.clone(), v)
  702. else:
  703. vjps1 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  704. vjps2 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  705. output_numel = output.numel() if not fast_mode else 1
  706. jacobians1, types_ok, sizes_ok = _stack_and_check_tensors(
  707. vjps1, inputs, output_numel
  708. )
  709. jacobians2, _, _ = _stack_and_check_tensors(vjps2, inputs, output_numel)
  710. reentrant = _check_jacobians_equal(jacobians1, jacobians2, nondet_tol)
  711. if not types_ok and check_grad_dtypes:
  712. raise GradcheckError("Gradient has dtype mismatch")
  713. if not sizes_ok:
  714. raise GradcheckError("Analytical gradient has incorrect size")
  715. if not reentrant:
  716. raise GradcheckError(
  717. "Backward is not reentrant, i.e., running backward with "
  718. "same input and grad_output multiple times gives different values, "
  719. "although analytical gradient matches numerical gradient."
  720. f"The tolerance for nondeterminism was {nondet_tol}." + FAILED_NONDET_MSG
  721. )
  722. return jacobians1
  723. def _get_analytical_vJu_backward_mode(
  724. inputs, outputs, nondet_tol, check_grad_dtypes, all_v, all_u
  725. ):
  726. reduced_jacobians: list[list[torch.Tensor]] = []
  727. for output, v in zip(outputs, all_v):
  728. all_vJ = _check_analytical_jacobian_attributes(
  729. inputs, output, nondet_tol, check_grad_dtypes, fast_mode=True, v=v
  730. )
  731. jacobian_scalars: list[torch.Tensor] = []
  732. for vJ, u in zip(all_vJ, all_u):
  733. # Why do we need squeeze here? vJ is a 2-d tensor so that we can reuse
  734. # the error checking logic from slow mode
  735. vJ = vJ.T.squeeze(0)
  736. if vJ.is_complex(): # C -> R
  737. tv = torch.view_as_real(vJ.resolve_conj())
  738. tr = tv.select(-1, 0)
  739. ti = tv.select(-1, 1)
  740. jacobian_scalars.append(tr.dot(u[0]) + 1j * ti.dot(u[1]))
  741. else: # R -> R
  742. jacobian_scalars.append(vJ.dot(u))
  743. reduced_jacobians.append(jacobian_scalars)
  744. return reduced_jacobians
  745. @deprecated(
  746. "`get_analytical_jacobian` was part of PyTorch's private API and not "
  747. "meant to be exposed. We are deprecating it and it will be removed "
  748. "in a future version of PyTorch. If you have a specific use for "
  749. "this or feature request for this to be a stable API, please file "
  750. "us an issue at https://github.com/pytorch/pytorch/issues/new",
  751. category=FutureWarning,
  752. )
  753. def get_analytical_jacobian(inputs, output, nondet_tol=0.0, grad_out=1.0):
  754. # Replicates the behavior of the old get_analytical_jacobian before the refactor
  755. # This shares much of its code with _check_analytical_jacobian_attributes
  756. if (
  757. grad_out != 1.0
  758. ): # grad_out param is only kept for backward compatibility reasons
  759. raise ValueError(
  760. "Expected grad_out to be 1.0. get_analytical_jacobian no longer "
  761. "supports values of grad_out != 1.0."
  762. )
  763. if output.is_complex():
  764. raise ValueError(
  765. "Expected output to be non-complex. get_analytical_jacobian no "
  766. "longer supports functions that return complex outputs."
  767. )
  768. diff_input_list = list(_iter_tensors(inputs, True))
  769. def vjp_fn(grad_output):
  770. return torch.autograd.grad(
  771. output, diff_input_list, grad_output, retain_graph=True, allow_unused=True
  772. )
  773. # Compute everything twice to check for nondeterminism (which we call reentrancy)
  774. vjps1 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  775. vjps2 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  776. output_numel = output.numel()
  777. jacobians1, types_ok, sizes_ok = _stack_and_check_tensors(
  778. vjps1, inputs, output_numel
  779. )
  780. jacobians2, _, _ = _stack_and_check_tensors(vjps2, inputs, output_numel)
  781. reentrant = _check_jacobians_equal(jacobians1, jacobians2, nondet_tol)
  782. return jacobians1, reentrant, sizes_ok, types_ok
  783. def _get_analytical_jacobian(inputs, outputs, input_idx, output_idx):
  784. # Computes the analytical Jacobian in slow mode for a single input-output pair.
  785. # Forgoes performing checks on dtype, shape, and reentrancy.
  786. jacobians = _check_analytical_jacobian_attributes(
  787. inputs, outputs[output_idx], nondet_tol=float("inf"), check_grad_dtypes=False
  788. )
  789. return jacobians[input_idx]
  790. def _compute_analytical_jacobian_rows(
  791. vjp_fn, sample_output
  792. ) -> list[list[Optional[torch.Tensor]]]:
  793. # Computes Jacobian row-by-row by projecting `vjp_fn` = v^T J on standard basis
  794. # vectors: vjp_fn(e) = e^T J is a corresponding row of the Jacobian.
  795. # NB: this function does not assume vjp_fn(v) to return tensors with the same
  796. # number of elements for different v. This is checked when we later combine the
  797. # rows into a single tensor.
  798. grad_out_base = torch.zeros_like(
  799. sample_output, memory_format=torch.legacy_contiguous_format
  800. )
  801. flat_grad_out = grad_out_base.view(-1)
  802. # jacobians_rows[i][j] is the Jacobian jth row for the ith input
  803. jacobians_rows: list[list[Optional[torch.Tensor]]] = []
  804. for j in range(flat_grad_out.numel()):
  805. flat_grad_out.zero_()
  806. flat_grad_out[j] = 1.0 # projection for jth row of Jacobian
  807. grad_inputs = vjp_fn(grad_out_base)
  808. for i, d_x in enumerate(grad_inputs):
  809. if j == 0:
  810. jacobians_rows.append([])
  811. jacobians_rows[i] += [
  812. d_x.clone() if isinstance(d_x, torch.Tensor) else None
  813. ]
  814. return jacobians_rows
  815. def _get_analytical_vjps_wrt_specific_output(
  816. vjp_fn, sample_output, v
  817. ) -> list[list[Optional[torch.Tensor]]]:
  818. grad_inputs = vjp_fn(v.reshape(sample_output.shape))
  819. vjps: list[list[Optional[torch.Tensor]]] = [
  820. [vjp.clone() if isinstance(vjp, torch.Tensor) else None] for vjp in grad_inputs
  821. ]
  822. return vjps
  823. def _check_inputs(tupled_inputs) -> bool:
  824. # Make sure that gradients are saved for at least one input
  825. any_input_requiring_grad = False
  826. for idx, inp in enumerate(tupled_inputs):
  827. if is_tensor_like(inp) and inp.requires_grad:
  828. if not (inp.dtype == torch.float64 or inp.dtype == torch.complex128):
  829. warnings.warn(
  830. f"Input #{idx} requires gradient and "
  831. "is not a double precision floating point or complex. "
  832. "This check will likely fail if all the inputs are "
  833. "not of double precision floating point or complex. ",
  834. stacklevel=2,
  835. )
  836. if inp.is_sparse:
  837. content = inp._values()
  838. elif _is_sparse_compressed_tensor(inp):
  839. content = inp.values()
  840. else:
  841. content = inp
  842. # TODO: To cover more problematic cases, replace stride = 0 check with
  843. # "any overlap in memory" once we have a proper function to check it.
  844. if content.layout is not torch._mkldnn: # type: ignore[attr-defined]
  845. if not all(
  846. st > 0 or sz <= 1
  847. for st, sz in zip(content.stride(), content.size())
  848. ):
  849. raise RuntimeError(
  850. f"The {idx}th input has a dimension with stride 0. gradcheck only "
  851. "supports inputs that are non-overlapping to be able to "
  852. "compute the numerical gradients correctly. You should call "
  853. ".contiguous on the input before passing it to gradcheck."
  854. )
  855. any_input_requiring_grad = True
  856. if not any_input_requiring_grad:
  857. raise ValueError(
  858. "gradcheck expects at least one input tensor to require gradient, "
  859. "but none of the them have requires_grad=True."
  860. )
  861. return True
  862. def _check_outputs(outputs) -> None:
  863. if any(_is_sparse_any_tensor(t) for t in outputs if isinstance(t, torch.Tensor)):
  864. # it is easier to call to_dense() on the sparse output than
  865. # to modify analytical jacobian
  866. raise ValueError(
  867. "Sparse output is not supported at gradcheck yet. "
  868. "Please call to_dense(masked_grad=...) on the output of fn for gradcheck."
  869. )
  870. if any(t.layout == torch._mkldnn for t in outputs if isinstance(t, torch.Tensor)): # type: ignore[attr-defined]
  871. raise ValueError(
  872. "MKLDNN output is not supported at gradcheck yet. "
  873. "Please call to_dense(masked_grad=...) on the output of fn for gradcheck."
  874. )
  875. def _check_no_differentiable_outputs(
  876. func, inputs, func_out, eps, *, is_forward_ad
  877. ) -> bool:
  878. # When there are no differentiable outputs, numerical gradient for a function is
  879. # expected to be zero.
  880. jacobians_all_inputs_outputs = _get_numerical_jacobian(
  881. func, inputs, func_out, eps=eps, is_forward_ad=is_forward_ad
  882. )
  883. for jacobians_all_outputs_and_fixed_input in jacobians_all_inputs_outputs:
  884. for jacobian in jacobians_all_outputs_and_fixed_input:
  885. if torch.ne(jacobian, 0).sum() > 0:
  886. raise GradcheckError(
  887. "Numerical gradient for function expected to be zero"
  888. )
  889. return True
  890. def _check_no_differentiable_outputs_fast(
  891. func, func_out, all_inputs, inputs_indices, all_u, eps, nondet_tol
  892. ):
  893. for inp_idx, u in zip(inputs_indices, all_u):
  894. jvps = _get_numerical_jvp_wrt_specific_input(func, inp_idx, all_inputs, u, eps)
  895. for jvp in jvps:
  896. if jvp.numel() == 0:
  897. continue
  898. if (jvp - torch.zeros_like(jvp)).abs().max() > nondet_tol:
  899. raise GradcheckError(
  900. "Numerical gradient for function expected to be zero"
  901. )
  902. return True
  903. FAILED_BATCHED_GRAD_MSG = """
  904. gradcheck or gradgradcheck failed while testing batched gradient computation.
  905. This could have been invoked in a number of ways (via a test that calls
  906. gradcheck/gradgradcheck directly or via an autogenerated test).
  907. If you are adding a new operator, please file an issue and then use one of the
  908. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  909. If the test
  910. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  911. with `check_batched_grad=False` as a keyword argument.
  912. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  913. to have `check_batched_grad=False` and/or `check_batched_gradgrad=False`.
  914. If you're modifying an existing operator that supports batched grad computation,
  915. or wish to make a new operator work with batched grad computation, please read
  916. the following.
  917. To compute batched grads (e.g., jacobians, hessians), we vmap over the backward
  918. computation. The most common failure case is if there is a 'vmap-incompatible
  919. operation' in the backward pass. Please see
  920. NOTE: [How to write vmap-compatible backward formulas]
  921. in the codebase for an explanation of how to fix this.
  922. """.strip()
  923. FAILED_BATCHED_GRAD_MSG_FWD_AD = """
  924. gradcheck failed while testing batched gradient computation with forward-mode AD.
  925. This test is enabled automatically when both `check_batched_grad=True`
  926. and `check_forward_ad=True`, but can be disabled in the following ways
  927. dependong on how the test was invoked (via a test that calls gradcheck
  928. directly or via an autogenerated test).
  929. If you are adding a new operator, please file an issue and then use one of the
  930. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  931. If the test
  932. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  933. with `check_batched_forward_grad=False` as a keyword argument.
  934. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  935. to have `check_batched_forward_grad=False`
  936. """
  937. def _get_failed_batched_grad_test_msg(
  938. output_idx, input_idx, res, exp, is_forward_ad=False
  939. ):
  940. return f"""
  941. For output {output_idx} and input {input_idx}:
  942. {FAILED_BATCHED_GRAD_MSG_FWD_AD if is_forward_ad else FAILED_BATCHED_GRAD_MSG}
  943. Got:
  944. {res}
  945. Expected:
  946. {exp}
  947. """.strip()
  948. def _test_batched_grad_forward_ad(func, inputs) -> bool:
  949. fwAD = torch.autograd.forward_ad # To avoid early import issues (do we need this?)
  950. if not isinstance(inputs, tuple):
  951. raise AssertionError("Expected inputs to be a tuple")
  952. for input_idx, current_input in enumerate(inputs):
  953. if not (is_tensor_like(current_input) and current_input.requires_grad):
  954. continue
  955. def jvp(tangent: torch.Tensor):
  956. with fwAD.dual_level():
  957. dual = fwAD.make_dual(current_input.detach(), tangent)
  958. inputs_with_dual = tuple(
  959. dual
  960. if idx == input_idx
  961. else (inp.detach() if is_tensor_like(inp) else inp)
  962. for idx, inp in enumerate(inputs)
  963. )
  964. dual_outputs = _as_tuple(func(*inputs_with_dual))
  965. ret = []
  966. for dual_output in dual_outputs:
  967. if dual_output is None:
  968. continue
  969. primal_out, tangent_out = fwAD.unpack_dual(dual_output)
  970. if tangent_out is not None:
  971. ret.append(tangent_out)
  972. else:
  973. ret.append(
  974. torch.zeros(
  975. [], dtype=primal_out.dtype, device=primal_out.device
  976. ).expand(primal_out.shape)
  977. )
  978. return tuple(ret)
  979. if not _is_float_or_complex_tensor(current_input):
  980. continue
  981. tangents = [torch.randn_like(current_input) for _ in range(2)]
  982. expected = [jvp(t) for t in tangents]
  983. expected = [torch.stack(shards) for shards in zip(*expected)]
  984. try:
  985. result = _vmap(jvp)(torch.stack(tangents))
  986. except RuntimeError as ex:
  987. # Rethrow to provide a better error message
  988. raise GradcheckError(
  989. f"While computing batched gradients, got: {ex}\n\n{FAILED_BATCHED_GRAD_MSG_FWD_AD}"
  990. ) from ex
  991. for input_idx, (res, exp) in enumerate(zip(result, expected)):
  992. if torch.allclose(res, exp):
  993. continue
  994. raise GradcheckError(
  995. _get_failed_batched_grad_test_msg(
  996. input_idx, input_idx, res, exp, is_forward_ad=True
  997. )
  998. )
  999. return True
  1000. def _test_batched_grad(input, output, output_idx) -> bool:
  1001. # NB: _test_batched_grad compares two autograd.grad invocations with a single
  1002. # vmap(autograd.grad) invocation. It's not exactly a "gradcheck" in the
  1003. # sense that we're not comparing an analytical jacobian with a numeric one,
  1004. # but it is morally similar (we could have computed a full analytic jac
  1005. # via vmap, but that is potentially slow)
  1006. diff_input_list = list(_iter_tensors(input, True))
  1007. grad = functools.partial(
  1008. torch.autograd.grad,
  1009. output,
  1010. diff_input_list,
  1011. retain_graph=True,
  1012. allow_unused=True,
  1013. )
  1014. def vjp(v):
  1015. results = grad(v)
  1016. results = tuple(
  1017. grad
  1018. if grad is not None
  1019. else torch.zeros([], dtype=inp.dtype, device=inp.device).expand(inp.shape)
  1020. for grad, inp in zip(results, diff_input_list)
  1021. )
  1022. return results
  1023. grad_outputs = [torch.randn_like(output) for _ in range(2)]
  1024. expected = [vjp(gO) for gO in grad_outputs]
  1025. expected = [torch.stack(shards) for shards in zip(*expected)]
  1026. # Squash warnings since these are expected to happen in most cases
  1027. # NB: this doesn't work for CUDA tests: https://github.com/pytorch/pytorch/issues/50209
  1028. with warnings.catch_warnings():
  1029. warnings.filterwarnings("ignore", message="There is a performance drop")
  1030. warnings.filterwarnings("ignore", message="Please use `torch.vmap`")
  1031. try:
  1032. result = vmap(vjp)(torch.stack(grad_outputs))
  1033. except RuntimeError as ex:
  1034. # It's OK that we're not raising the error at the correct callsite.
  1035. # That's because the callsite is always going to inside the Python
  1036. # autograd.grad instead of the C++ traceback of what line in the
  1037. # backward formula
  1038. raise GradcheckError(
  1039. f"While computing batched gradients, got: {ex}\n\n{FAILED_BATCHED_GRAD_MSG}"
  1040. ) from ex
  1041. for input_idx, (res, exp) in enumerate(zip(result, expected)):
  1042. if torch.allclose(res, exp):
  1043. continue
  1044. raise GradcheckError(
  1045. _get_failed_batched_grad_test_msg(output_idx, input_idx, res, exp)
  1046. )
  1047. return True
  1048. def _test_backward_mul_by_grad_output(outputs, inputs, masked) -> bool:
  1049. # Tests that backward is multiplied by grad_output
  1050. diff_input_list: list[torch.Tensor] = list(_iter_tensors(inputs, True))
  1051. if not diff_input_list:
  1052. raise GradcheckError("no Tensors requiring grad found in input")
  1053. grads_input = torch.autograd.grad(
  1054. outputs,
  1055. diff_input_list,
  1056. [
  1057. torch.zeros_like(o, memory_format=torch.legacy_contiguous_format)
  1058. for o in outputs
  1059. ],
  1060. allow_unused=True,
  1061. )
  1062. for gi, di in zip(grads_input, diff_input_list):
  1063. if gi is None:
  1064. continue
  1065. if isinstance(gi, torch.Tensor) and gi.layout != torch.strided:
  1066. if gi.layout != di.layout:
  1067. raise GradcheckError(
  1068. "grad is incorrect layout ("
  1069. + str(gi.layout)
  1070. + " is not "
  1071. + str(di.layout)
  1072. + ")"
  1073. )
  1074. if _is_sparse_any_tensor(gi):
  1075. sparse_kind = str(gi.layout).replace("torch.", "").replace("_coo", "")
  1076. if gi.sparse_dim() != di.sparse_dim():
  1077. raise GradcheckError(
  1078. f"grad is {sparse_kind} tensor, but has incorrect sparse_dim"
  1079. f" {gi.sparse_dim()}, expected {di.sparse_dim()}"
  1080. )
  1081. if gi.dense_dim() != di.dense_dim():
  1082. raise GradcheckError(
  1083. f"grad is {sparse_kind} tensor, but has incorrect dense_dim"
  1084. f" {gi.dense_dim()}, expected {di.dense_dim()}"
  1085. )
  1086. gi = gi.to_dense()
  1087. di = di.to_dense()
  1088. if masked:
  1089. if not torch.allclose(gi, torch.zeros_like(gi)):
  1090. raise GradcheckError("backward not multiplied by grad_output")
  1091. elif not gi.eq(0).all():
  1092. raise GradcheckError("backward not multiplied by grad_output")
  1093. if gi.dtype != di.dtype:
  1094. raise GradcheckError("grad is incorrect type")
  1095. if gi.device != di.device:
  1096. raise GradcheckError("grad is incorrect device")
  1097. if gi.size() != di.size():
  1098. raise GradcheckError("grad is incorrect size")
  1099. return True
  1100. def _test_undefined_forward_mode(func, outputs, inputs):
  1101. fwAD = torch.autograd.forward_ad
  1102. _inp_tensors_idx, inp_tensors = _get_inp_tensors(inputs)
  1103. _all_v, all_u, _all_u_dense = _make_vectors(
  1104. inp_tensors, outputs, use_forward_ad=True
  1105. )
  1106. with fwAD.dual_level():
  1107. fw_grads = []
  1108. dual_inputs = []
  1109. tensor_indices = set()
  1110. for i, inp in enumerate(inputs):
  1111. if is_tensor_like(inp) and inp.requires_grad:
  1112. if inp.layout == torch._mkldnn: # type: ignore[attr-defined]
  1113. raise ValueError(
  1114. "MKLDNN inputs are not support for forward AD gradcheck."
  1115. )
  1116. inp = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  1117. # If inp is a differentiable view, the dual might not be the tangent given to
  1118. # make_dual, so read it explicitly from the dual tensor
  1119. fw_grads.append(fwAD.unpack_dual(inp)[1])
  1120. tensor_indices.add(i)
  1121. dual_inputs.append(inp)
  1122. for fw_grad, u in zip(fw_grads, all_u):
  1123. fw_grad.copy_(u.view_as(fw_grad))
  1124. for idx, inp in enumerate(inputs):
  1125. if idx not in tensor_indices:
  1126. continue
  1127. dual_inp_obj = dual_inputs[idx]
  1128. # case 1 (Materialized Zero Tensor Tangent)
  1129. dual_inputs[idx] = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  1130. raw_outputs = _as_tuple(func(*dual_inputs))
  1131. dual_outputs1 = filter(_is_float_or_complex_tensor, raw_outputs)
  1132. # case 2 (Efficient Zero Tensor Tangent since we don't make a dual object and pass a regular tensor)
  1133. dual_inputs[idx] = inp.detach()
  1134. raw_outputs = _as_tuple(func(*dual_inputs))
  1135. dual_outputs2 = filter(_is_float_or_complex_tensor, raw_outputs)
  1136. # reset
  1137. dual_inputs[idx] = dual_inp_obj
  1138. for index_o, (d_o1, d_o2) in enumerate(zip(dual_outputs1, dual_outputs2)):
  1139. _val1, res1 = fwAD.unpack_dual(d_o1)
  1140. _val2, res2 = fwAD.unpack_dual(d_o2)
  1141. if not (res1 is None or res2 is None):
  1142. if not torch.allclose(res1, res2):
  1143. raise GradcheckError(
  1144. "Mismatch in tangent values for output with index: ",
  1145. index_o,
  1146. " when input: ",
  1147. inp,
  1148. " has an undefined tangent value. ",
  1149. " Got: ",
  1150. res1,
  1151. " but expected: ",
  1152. res2,
  1153. )
  1154. return True
  1155. def _test_undefined_backward_mode(func, outputs, inputs) -> bool:
  1156. diff_input_list: list[torch.Tensor] = list(_iter_tensors(inputs, True))
  1157. if not diff_input_list:
  1158. raise GradcheckError("no Tensors requiring grad found in input")
  1159. def warn_bc_breaking():
  1160. warnings.warn(
  1161. "Backwards compatibility: New undefined gradient support checking "
  1162. "feature is enabled by default, but it may break existing callers "
  1163. "of this function. If this is true for you, you can call this "
  1164. 'function with "check_undefined_grad=False" to disable the feature',
  1165. stacklevel=2,
  1166. )
  1167. def check_undefined_grad_support(output_to_check):
  1168. grads_output = [
  1169. torch.zeros_like(o, memory_format=torch.legacy_contiguous_format)
  1170. for o in output_to_check
  1171. ]
  1172. try:
  1173. grads_input = torch.autograd.grad(
  1174. output_to_check, diff_input_list, grads_output, allow_unused=True
  1175. )
  1176. except RuntimeError as e:
  1177. warn_bc_breaking()
  1178. raise GradcheckError(
  1179. "Expected backward function to handle undefined output grads. "
  1180. 'Please look at "Notes about undefined output gradients" in '
  1181. '"tools/autograd/derivatives.yaml"'
  1182. ) from e
  1183. for gi in grads_input:
  1184. if (gi is not None) and (not gi.eq(0).all()):
  1185. warn_bc_breaking()
  1186. raise GradcheckError(
  1187. "Expected all input grads to be undefined or zero when all output grads are undefined "
  1188. 'or zero. Please look at "Notes about undefined output gradients" in '
  1189. '"tools/autograd/derivatives.yaml"'
  1190. )
  1191. return True
  1192. # All backward functions must work properly if all output grads are undefined
  1193. outputs_to_check = [
  1194. [
  1195. torch._C._functions.UndefinedGrad()(o)
  1196. for o in _differentiable_outputs(func(*inputs))
  1197. # This check filters out Tensor-likes that aren't instances of Tensor.
  1198. if isinstance(o, torch.Tensor)
  1199. ]
  1200. ]
  1201. # If there are multiple output grads, we should be able to undef one at a time without error
  1202. if len(outputs_to_check[0]) > 1:
  1203. for undef_grad_idx in range(len(outputs)):
  1204. output_to_check = _differentiable_outputs(func(*inputs))
  1205. outputs_to_check.append(
  1206. [
  1207. torch._C._functions.UndefinedGrad()(o)
  1208. if idx == undef_grad_idx
  1209. else o
  1210. for idx, o in enumerate(output_to_check)
  1211. ]
  1212. )
  1213. return all(check_undefined_grad_support(output) for output in outputs_to_check)
  1214. def _as_tuple(x):
  1215. if isinstance(x, tuple):
  1216. return x
  1217. elif isinstance(x, list):
  1218. return tuple(x)
  1219. else:
  1220. return (x,)
  1221. def _differentiable_outputs(x):
  1222. return tuple(o for o in _as_tuple(x) if o.requires_grad)
  1223. def _get_notallclose_msg(
  1224. analytical,
  1225. numerical,
  1226. output_idx,
  1227. input_idx,
  1228. complex_indices,
  1229. test_imag=False,
  1230. is_forward_ad=False,
  1231. ) -> str:
  1232. out_is_complex = (
  1233. (not is_forward_ad) and complex_indices and output_idx in complex_indices
  1234. )
  1235. inp_is_complex = is_forward_ad and complex_indices and input_idx in complex_indices
  1236. part = "imaginary" if test_imag else "real"
  1237. element = "inputs" if is_forward_ad else "outputs"
  1238. prefix = (
  1239. ""
  1240. if not (out_is_complex or inp_is_complex)
  1241. else f"While considering the {part} part of complex {element} only, "
  1242. )
  1243. mode = "computed with forward mode " if is_forward_ad else ""
  1244. return (
  1245. prefix
  1246. + f"Jacobian {mode}mismatch for output {output_idx:d} with respect to input {input_idx:d},\n"
  1247. f"numerical:{numerical}\nanalytical:{analytical}\n"
  1248. )
  1249. def _transpose(matrix_of_tensors):
  1250. # returns list of tuples
  1251. return list(zip(*matrix_of_tensors))
  1252. def _real_and_imag_output(fn):
  1253. # returns new functions real(fn), and imag(fn) where real(fn) and imag(fn) behave the same as
  1254. # the original fn, except torch.real or torch.imag are applied to the complex outputs
  1255. def apply_to_c_outs(fn, fn_to_apply):
  1256. def wrapped_fn(*inputs):
  1257. outs = _as_tuple(fn(*inputs))
  1258. return tuple(fn_to_apply(o) if o.is_complex() else o for o in outs)
  1259. return wrapped_fn
  1260. return apply_to_c_outs(fn, torch.real), apply_to_c_outs(fn, torch.imag)
  1261. def _real_and_imag_input(fn, complex_inp_indices, tupled_inputs):
  1262. # returns new functions that take real inputs instead of complex inputs as
  1263. # (x, y) -> fn(x + y * 1j). And it computes: inp -> fn(inp + y * 1j) and inp -> fn(x + inp * 1j).
  1264. # In each case, the other part is considered constant.
  1265. # We do not use 0 for the constant here to make sure we always call the user function with a valid input.
  1266. def apply_to_c_inps(fn, fn_to_apply):
  1267. def wrapped_fn(*inputs):
  1268. new_inputs = list(inputs)
  1269. for should_be_complex in complex_inp_indices:
  1270. new_inputs[should_be_complex] = fn_to_apply(
  1271. new_inputs[should_be_complex], tupled_inputs[should_be_complex]
  1272. )
  1273. return _as_tuple(fn(*new_inputs))
  1274. return wrapped_fn
  1275. real_fn = apply_to_c_inps(fn, lambda inp, orig: inp + orig.imag * 1j)
  1276. imag_fn = apply_to_c_inps(fn, lambda inp, orig: orig.real + inp * 1j)
  1277. return real_fn, imag_fn
  1278. def _gradcheck_real_imag(
  1279. gradcheck_fn,
  1280. func,
  1281. func_out,
  1282. tupled_inputs,
  1283. outputs,
  1284. eps,
  1285. rtol,
  1286. atol,
  1287. check_grad_dtypes,
  1288. check_forward_ad,
  1289. check_backward_ad,
  1290. nondet_tol,
  1291. check_undefined_grad,
  1292. ):
  1293. complex_out_indices = [i for i, o in enumerate(outputs) if o.is_complex()]
  1294. has_any_complex_output = any(o.is_complex() for o in _as_tuple(func_out))
  1295. if check_backward_ad:
  1296. if has_any_complex_output:
  1297. real_fn, imag_fn = _real_and_imag_output(func)
  1298. imag_func_out = imag_fn(*tupled_inputs)
  1299. imag_outputs = _differentiable_outputs(imag_func_out)
  1300. gradcheck_fn(
  1301. imag_fn,
  1302. imag_func_out,
  1303. tupled_inputs,
  1304. imag_outputs,
  1305. eps,
  1306. rtol,
  1307. atol,
  1308. check_grad_dtypes,
  1309. nondet_tol,
  1310. complex_indices=complex_out_indices,
  1311. test_imag=True,
  1312. )
  1313. real_func_out = real_fn(*tupled_inputs)
  1314. real_outputs = _differentiable_outputs(real_func_out)
  1315. gradcheck_fn(
  1316. real_fn,
  1317. real_func_out,
  1318. tupled_inputs,
  1319. real_outputs,
  1320. eps,
  1321. rtol,
  1322. atol,
  1323. check_grad_dtypes,
  1324. nondet_tol,
  1325. complex_indices=complex_out_indices,
  1326. )
  1327. else:
  1328. gradcheck_fn(
  1329. func,
  1330. func_out,
  1331. tupled_inputs,
  1332. outputs,
  1333. eps,
  1334. rtol,
  1335. atol,
  1336. check_grad_dtypes,
  1337. nondet_tol,
  1338. )
  1339. if check_forward_ad:
  1340. complex_inp_indices = [
  1341. i
  1342. for i, inp in enumerate(tupled_inputs)
  1343. if is_tensor_like(inp) and inp.is_complex()
  1344. ]
  1345. if complex_inp_indices:
  1346. real_fn, imag_fn = _real_and_imag_input(
  1347. func, complex_inp_indices, tupled_inputs
  1348. )
  1349. imag_inputs = [
  1350. inp.imag if is_tensor_like(inp) and inp.is_complex() else inp
  1351. for inp in tupled_inputs
  1352. ]
  1353. imag_func_out = imag_fn(*imag_inputs)
  1354. diff_imag_func_out = _differentiable_outputs(imag_func_out)
  1355. gradcheck_fn(
  1356. imag_fn,
  1357. imag_func_out,
  1358. imag_inputs,
  1359. diff_imag_func_out,
  1360. eps,
  1361. rtol,
  1362. atol,
  1363. check_grad_dtypes,
  1364. nondet_tol,
  1365. complex_indices=complex_inp_indices,
  1366. test_imag=True,
  1367. use_forward_ad=True,
  1368. )
  1369. real_inputs = [
  1370. inp.real if is_tensor_like(inp) and inp.is_complex() else inp
  1371. for inp in tupled_inputs
  1372. ]
  1373. real_func_out = real_fn(*real_inputs)
  1374. diff_real_func_out = _differentiable_outputs(real_func_out)
  1375. gradcheck_fn(
  1376. real_fn,
  1377. real_func_out,
  1378. real_inputs,
  1379. diff_real_func_out,
  1380. eps,
  1381. rtol,
  1382. atol,
  1383. check_grad_dtypes,
  1384. nondet_tol,
  1385. complex_indices=complex_inp_indices,
  1386. use_forward_ad=True,
  1387. )
  1388. if check_undefined_grad:
  1389. _test_undefined_forward_mode(imag_fn, imag_func_out, imag_inputs)
  1390. _test_undefined_forward_mode(real_fn, real_func_out, real_inputs)
  1391. else:
  1392. gradcheck_fn(
  1393. func,
  1394. func_out,
  1395. tupled_inputs,
  1396. outputs,
  1397. eps,
  1398. rtol,
  1399. atol,
  1400. check_grad_dtypes,
  1401. nondet_tol,
  1402. use_forward_ad=True,
  1403. )
  1404. if check_undefined_grad:
  1405. _test_undefined_forward_mode(func, outputs, tupled_inputs)
  1406. def _slow_gradcheck(
  1407. func,
  1408. func_out,
  1409. tupled_inputs,
  1410. outputs,
  1411. eps,
  1412. rtol,
  1413. atol,
  1414. check_grad_dtypes,
  1415. nondet_tol,
  1416. *,
  1417. use_forward_ad=False,
  1418. complex_indices=None,
  1419. test_imag=False,
  1420. masked=False,
  1421. ):
  1422. func_out = _as_tuple(func_out)
  1423. if not outputs:
  1424. return _check_no_differentiable_outputs(
  1425. func, tupled_inputs, func_out, eps=eps, is_forward_ad=use_forward_ad
  1426. )
  1427. tupled_inputs_numerical = tupled_inputs if masked else _densify(tupled_inputs)
  1428. numerical = _transpose(
  1429. _get_numerical_jacobian(
  1430. func,
  1431. tupled_inputs_numerical,
  1432. func_out,
  1433. eps=eps,
  1434. is_forward_ad=use_forward_ad,
  1435. )
  1436. )
  1437. # Note: [numerical vs analytical output length]
  1438. # The numerical path returns jacobian quantity for all outputs, even if requires_grad of that
  1439. # output is False. This behavior is necessary for _check_no_differentiable_outputs to work.
  1440. numerical = [nj for o, nj in zip(func_out, numerical) if o.requires_grad]
  1441. if use_forward_ad:
  1442. analytical_forward = _get_analytical_jacobian_forward_ad(
  1443. func, tupled_inputs, func_out, check_grad_dtypes=check_grad_dtypes
  1444. )
  1445. for i, n_per_out in enumerate(numerical):
  1446. for j, n in enumerate(n_per_out):
  1447. a = analytical_forward[j][i]
  1448. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, atol):
  1449. raise GradcheckError(
  1450. _get_notallclose_msg(
  1451. a, n, i, j, complex_indices, test_imag, is_forward_ad=True
  1452. )
  1453. )
  1454. else:
  1455. for i, o in enumerate(outputs):
  1456. analytical = _check_analytical_jacobian_attributes(
  1457. tupled_inputs, o, nondet_tol, check_grad_dtypes
  1458. )
  1459. for j, (a, n) in enumerate(zip(analytical, numerical[i])):
  1460. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, atol):
  1461. raise GradcheckError(
  1462. _get_notallclose_msg(a, n, i, j, complex_indices, test_imag)
  1463. )
  1464. return True
  1465. def _dot_with_type_promotion(u, v):
  1466. if u.dim() != 1 or v.dim() != 1:
  1467. raise AssertionError(
  1468. f"Expected u and v to be 1D tensors, but got dims {u.dim()} and {v.dim()}"
  1469. )
  1470. return (u * v).sum()
  1471. def _allclose_with_type_promotion(a, b, rtol, atol):
  1472. promoted_type = torch.promote_types(a.dtype, b.dtype)
  1473. a = a.to(dtype=promoted_type)
  1474. b = b.to(dtype=promoted_type)
  1475. return torch.allclose(a, b, rtol, atol)
  1476. def _to_real_dtype(dtype):
  1477. if dtype == torch.complex128:
  1478. return torch.float64
  1479. elif dtype == torch.complex64:
  1480. return torch.float32
  1481. else:
  1482. return dtype
  1483. def _vec_from_tensor(x, generator, downcast_complex=False):
  1484. # Create a random vector with the same number of elements as x and the same
  1485. # dtype/device. If x is complex and downcast_complex is False, we create a
  1486. # complex tensor with only real component.
  1487. if x.layout == torch.sparse_coo:
  1488. # For sparse, create a random sparse vec with random values in the same
  1489. # indices. Make sure size is set so that it isn't inferred to be smaller.
  1490. x_values = x._values()
  1491. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1492. values = (
  1493. torch.rand(x_values.numel(), generator=generator)
  1494. .to(dtype=dtype, device=x.device)
  1495. .view(x_values.shape)
  1496. )
  1497. values /= values.norm()
  1498. vec = torch.sparse_coo_tensor(x._indices(), values, x.size(), device=x.device)
  1499. elif _is_sparse_compressed_tensor(x):
  1500. if x.layout in {torch.sparse_csr, torch.sparse_bsr}:
  1501. compressed_indices, plain_indices = x.crow_indices(), x.col_indices()
  1502. else:
  1503. compressed_indices, plain_indices = x.ccol_indices(), x.row_indices()
  1504. x_values = x.values()
  1505. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1506. values = (
  1507. torch.rand(x_values.numel(), generator=generator)
  1508. .to(dtype=dtype, device=x.device)
  1509. .view(x_values.shape)
  1510. )
  1511. values /= values.norm()
  1512. vec = torch.sparse_compressed_tensor(
  1513. compressed_indices,
  1514. plain_indices,
  1515. values,
  1516. x.size(),
  1517. layout=x.layout,
  1518. device=x.device,
  1519. )
  1520. else:
  1521. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1522. vec = torch.rand(x.numel(), generator=generator).to(
  1523. dtype=dtype, device=x.device
  1524. )
  1525. vec /= vec.norm()
  1526. return vec
  1527. def _get_inp_tensors(tupled_inputs):
  1528. inp_idx_tup = [
  1529. (i, t)
  1530. for i, t in enumerate(tupled_inputs)
  1531. if is_tensor_like(t) and t.requires_grad
  1532. ]
  1533. return [tup[0] for tup in inp_idx_tup], [tup[1] for tup in inp_idx_tup]
  1534. def _adjusted_atol(atol, u, v):
  1535. # In slow gradcheck, we compare A and B element-wise, i.e., for some a, b we
  1536. # allow: |a - b| < atol + rtol * b. But since we now compare q1 = v^T A u and
  1537. # q2 = v^T B u, we must allow |q1 - q2| < v^T E u + rtol * v^T B u, where E is
  1538. # the correctly sized matrix in which each entry is atol.
  1539. #
  1540. # We see that atol needs to be scaled by v^T M u (where M is an all-ones M x N
  1541. # matrix): v^T M u = \sum_{i} \sum_{j} u[i] * v[j] = sum(u) * sum(v).
  1542. # For the case of complex inputs, u has re and im. components: u = (ur, ui).
  1543. # Let q = a - b = (qr, qi) in the above notation, eg. q is the difference between analytic and numerical
  1544. # Jacobians. Then the transformed tolerance checks being done in the torch.allclose ops
  1545. # are of form abs(Re{q_r u_r - q_i u_i}) < atol * (abs(u_r) + abs(u_i)), and equivalently
  1546. # for imaginary components abs(Im{q_r u_r - q_i ui}) < atol * (abs(u_r) + abs(u_i)).
  1547. # Since u is drawn randomly non-negative, the end effect is a factor
  1548. # (sum(u_r) + sum(u_i)) * sum(v) increase in atol for complex inputs, eg.
  1549. # a statistical factor of 2 as compared to the real case.
  1550. sum_v = 1.0 if v is None else v.sum()
  1551. if isinstance(u, tuple):
  1552. # case of complex input
  1553. ur, ui = u[0], u[1]
  1554. sum_ur = ur.sum()
  1555. sum_ui = ui.sum()
  1556. complex_modified_atol = atol * (float(sum_ur) + float(sum_ui)) * float(sum_v)
  1557. return complex_modified_atol
  1558. # case of real input
  1559. sum_u = u.sum()
  1560. modified_atol = atol * float(sum_u) * float(sum_v)
  1561. return modified_atol
  1562. FAST_FAIL_SLOW_OK_MSG = """
  1563. Fast gradcheck failed but element-wise differences are small. This means that the
  1564. test might've passed in slow_mode!
  1565. If you are adding a new operator, please file an issue and then use one of the
  1566. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck:
  1567. If the test
  1568. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  1569. with `fast_mode=False` as a keyword argument.
  1570. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  1571. to have `gradcheck_fast_mode=False`
  1572. - is a Module test (e.g., in common_nn.py), then modify the corresponding
  1573. module_test entry to have `gradcheck_fast_mode=False`
  1574. """.strip()
  1575. def _run_slow_mode_and_get_error(
  1576. func, tupled_inputs, outputs, input_idx, output_idx, rtol, atol, eps, is_forward_ad
  1577. ):
  1578. # Compute jacobians in slow mode for better error message
  1579. slow_numerical = _get_numerical_jacobian(
  1580. func, tupled_inputs, outputs, eps=eps, is_forward_ad=is_forward_ad
  1581. )[input_idx][output_idx]
  1582. if is_forward_ad:
  1583. def new_fn(inp):
  1584. new_inputs = list(tupled_inputs)
  1585. new_inputs[input_idx] = inp
  1586. return _as_tuple(func(*new_inputs))[output_idx]
  1587. slow_analytical = _get_analytical_jacobian_forward_ad(
  1588. new_fn, (tupled_inputs[input_idx],), (outputs[output_idx],)
  1589. )[0][0]
  1590. else:
  1591. slow_analytical = _get_analytical_jacobian(
  1592. tupled_inputs, outputs, input_idx, output_idx
  1593. )
  1594. # Assume jacobians are non-empty and have the same shape
  1595. slow_max_diff = (slow_numerical - slow_analytical).abs().max()
  1596. slow_allclose = torch.allclose(slow_analytical, slow_numerical, rtol, atol)
  1597. msg = (
  1598. "\nThe above quantities relating the numerical and analytical jacobians are computed \n"
  1599. "in fast mode. See: https://github.com/pytorch/pytorch/issues/53876 for more background \n"
  1600. "about fast mode. Below, we recompute numerical and analytical jacobians in slow mode:\n\n"
  1601. f"Numerical:\n {slow_numerical}\n"
  1602. f"Analytical:\n{slow_analytical}\n\n"
  1603. f"The max per-element difference (slow mode) is: {slow_max_diff}.\n"
  1604. )
  1605. if slow_allclose:
  1606. # Slow gradcheck would've passed!
  1607. msg += FAST_FAIL_SLOW_OK_MSG
  1608. return msg
  1609. def _to_flat_dense_if_sparse(tensor):
  1610. if _is_sparse_any_tensor(tensor):
  1611. return tensor.to_dense().reshape(-1)
  1612. else:
  1613. return tensor
  1614. def _make_vectors(inp_tensors, outputs, *, use_forward_ad):
  1615. # Use our own generator to avoid messing with the user's RNG state
  1616. g_cpu = torch.Generator()
  1617. def _vec_from_tensor_cpu(*args):
  1618. # Default allocate all tensors on CPU, so they are on the same device as the generator
  1619. # even if the user specified a default device
  1620. with torch.device("cpu"):
  1621. return _vec_from_tensor(*args)
  1622. all_u = []
  1623. all_u_dense = []
  1624. for inp in inp_tensors:
  1625. ur = _vec_from_tensor_cpu(inp, g_cpu, True)
  1626. ur_dense = _to_flat_dense_if_sparse(ur)
  1627. if inp.is_complex():
  1628. ui = _vec_from_tensor_cpu(inp, g_cpu, True)
  1629. all_u.append((ur, ui))
  1630. ui_dense = _to_flat_dense_if_sparse(ui)
  1631. all_u_dense.append((ur_dense, ui_dense))
  1632. else:
  1633. all_u.append(ur)
  1634. all_u_dense.append(ur_dense)
  1635. all_v = (
  1636. None
  1637. if use_forward_ad
  1638. else [_vec_from_tensor_cpu(out, g_cpu) for out in outputs]
  1639. )
  1640. return all_v, all_u, all_u_dense
  1641. def _check_analytical_numerical_equal(
  1642. all_analytical,
  1643. all_numerical,
  1644. complex_indices,
  1645. tupled_inputs,
  1646. outputs,
  1647. func,
  1648. all_v,
  1649. all_u,
  1650. rtol,
  1651. atol,
  1652. eps,
  1653. test_imag,
  1654. *,
  1655. is_forward_ad=False,
  1656. ):
  1657. for i, all_numerical_for_input_i in enumerate(all_numerical):
  1658. for j, n in enumerate(all_numerical_for_input_i):
  1659. # Forward AD generates the transpose of what this function expects
  1660. if is_forward_ad:
  1661. a = all_analytical[i][j]
  1662. else:
  1663. a = all_analytical[j][i]
  1664. n = n.to(device=a.device)
  1665. updated_atol = _adjusted_atol(atol, all_u[i], all_v[j] if all_v else None)
  1666. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, updated_atol):
  1667. jacobians_str = _run_slow_mode_and_get_error(
  1668. func, tupled_inputs, outputs, i, j, rtol, atol, eps, is_forward_ad
  1669. )
  1670. raise GradcheckError(
  1671. _get_notallclose_msg(
  1672. a, n, j, i, complex_indices, test_imag, is_forward_ad
  1673. )
  1674. + jacobians_str
  1675. )
  1676. def _fast_gradcheck(
  1677. func,
  1678. func_out,
  1679. inputs,
  1680. outputs,
  1681. eps,
  1682. rtol,
  1683. atol,
  1684. check_grad_dtypes,
  1685. nondet_tol,
  1686. *,
  1687. use_forward_ad=False,
  1688. complex_indices=None,
  1689. test_imag=False,
  1690. masked=False,
  1691. ):
  1692. # See https://github.com/pytorch/pytorch/issues/53876 for details
  1693. inp_tensors_idx, inp_tensors = _get_inp_tensors(inputs)
  1694. # Backward mode computes v^T * J (VJP)
  1695. # Since we computed J * u (JVP) through finite difference method, we perform an equality check
  1696. # between VJP * u, v * JVP
  1697. # ----
  1698. # Forward mode computes J * u (JVP)
  1699. # Since we already compute JVP through finite difference method,
  1700. # we don't need v for correctness check here as asserted below
  1701. all_v, all_u, all_u_dense = _make_vectors(
  1702. inp_tensors, outputs, use_forward_ad=use_forward_ad
  1703. )
  1704. inputs_numerical, all_u_numerical, all_v_numerical = (
  1705. (inputs, all_u, all_v) if masked else _densify((inputs, all_u, all_v))
  1706. )
  1707. numerical_vJu = _get_numerical_vJu(
  1708. func,
  1709. inputs_numerical,
  1710. inp_tensors_idx,
  1711. func_out,
  1712. all_u_numerical,
  1713. all_v_numerical,
  1714. eps,
  1715. is_forward_ad=use_forward_ad,
  1716. )
  1717. # TODO: replicate https://github.com/pytorch/pytorch/pull/77743 for fast gradcheck as well
  1718. if use_forward_ad:
  1719. if all_v is not None:
  1720. raise AssertionError("Expected all_v to be None.")
  1721. analytical_vJu = _get_analytical_jacobian_forward_ad(
  1722. func,
  1723. inputs,
  1724. _as_tuple(func_out),
  1725. all_u=all_u,
  1726. check_grad_dtypes=check_grad_dtypes,
  1727. )
  1728. else:
  1729. if not outputs:
  1730. _check_no_differentiable_outputs_fast(
  1731. func, func_out, inputs, inp_tensors_idx, all_u, eps, nondet_tol
  1732. )
  1733. analytical_vJu = _get_analytical_vJu_backward_mode(
  1734. inputs, outputs, nondet_tol, check_grad_dtypes, all_v, all_u_dense
  1735. )
  1736. _check_analytical_numerical_equal(
  1737. analytical_vJu,
  1738. numerical_vJu,
  1739. complex_indices,
  1740. inputs,
  1741. outputs,
  1742. func,
  1743. all_v,
  1744. all_u,
  1745. rtol,
  1746. atol,
  1747. eps,
  1748. test_imag,
  1749. is_forward_ad=use_forward_ad,
  1750. )
  1751. return True
  1752. # Note [VarArg of Tensors]
  1753. # ~~~~~~~~~~~~~~~~~~~~~~~~
  1754. # 'func' accepts a vararg of tensors, which isn't expressible in the type system at the moment.
  1755. # If https://mypy.readthedocs.io/en/latest/additional_features.html?highlight=callable#extended-callable-types is accepted,
  1756. # the '...' first argument of Callable can be replaced with VarArg(Tensor).
  1757. # For now, we permit any input.
  1758. def gradcheck(
  1759. func: Callable[..., Union[_TensorOrTensors]], # See Note [VarArg of Tensors]
  1760. inputs: _TensorOrTensors,
  1761. *,
  1762. eps: float = 1e-6,
  1763. atol: float = 1e-5,
  1764. rtol: float = 1e-3,
  1765. raise_exception: bool = True,
  1766. nondet_tol: float = 0.0,
  1767. check_undefined_grad: bool = True,
  1768. check_grad_dtypes: bool = False,
  1769. check_batched_grad: bool = False,
  1770. check_batched_forward_grad: bool = False,
  1771. check_forward_ad: bool = False,
  1772. check_backward_ad: bool = True,
  1773. fast_mode: bool = False,
  1774. masked: Optional[bool] = None,
  1775. ) -> bool: # noqa: D400,D205
  1776. r"""Check gradients computed via small finite differences against analytical
  1777. gradients wrt tensors in :attr:`inputs` that are of floating point or complex type
  1778. and with ``requires_grad=True``.
  1779. The check between numerical and analytical gradients uses :func:`~torch.allclose`.
  1780. For most of the complex functions we consider for optimization purposes, no notion of
  1781. Jacobian exists. Instead, gradcheck verifies if the numerical and analytical values of
  1782. the Wirtinger and Conjugate Wirtinger derivatives are consistent. Because the gradient
  1783. computation is done under the assumption that the overall function has a real-valued
  1784. output, we treat functions with complex output in a special way. For these functions,
  1785. gradcheck is applied to two real-valued functions corresponding to taking the real
  1786. components of the complex outputs for the first, and taking the imaginary components
  1787. of the complex outputs for the second. For more details, check out
  1788. :ref:`complex_autograd-doc`.
  1789. .. note::
  1790. The default values are designed for :attr:`input` of double precision.
  1791. This check will likely fail if :attr:`input` is of less precision, e.g.,
  1792. ``FloatTensor``.
  1793. .. note::
  1794. Gradcheck may fail when evaluated on non-differentiable points
  1795. because the numerically computed gradients via finite differencing may differ
  1796. those computed analytically (not necessarily because either is incorrect).
  1797. For more context, see :ref:`non-differentiable-func-grad`.
  1798. .. warning::
  1799. If any checked tensor in :attr:`input` has overlapping memory, i.e.,
  1800. different indices pointing to the same memory address (e.g., from
  1801. :func:`torch.Tensor.expand`), this check will likely fail because the numerical
  1802. gradients computed by point perturbation at such indices will change
  1803. values at all other indices that share the same memory address.
  1804. Args:
  1805. func (function): a Python function that takes Tensor inputs and returns
  1806. a Tensor or a tuple of Tensors
  1807. inputs (tuple of Tensor or Tensor): inputs to the function
  1808. eps (float, optional): perturbation for finite differences
  1809. atol (float, optional): absolute tolerance
  1810. rtol (float, optional): relative tolerance
  1811. raise_exception (bool, optional): indicating whether to raise an exception if
  1812. the check fails. The exception gives more information about the
  1813. exact nature of the failure. This is helpful when debugging gradchecks.
  1814. nondet_tol (float, optional): tolerance for non-determinism. When running
  1815. identical inputs through the differentiation, the results must either match
  1816. exactly (default, 0.0) or be within this tolerance.
  1817. check_undefined_grad (bool, optional): if ``True``, check if undefined output grads
  1818. are supported and treated as zeros, for ``Tensor`` outputs.
  1819. check_batched_grad (bool, optional): if ``True``, check if we can compute
  1820. batched gradients using prototype vmap support. Defaults to False.
  1821. check_batched_forward_grad (bool, optional): if ``True``, checks if we can compute
  1822. batched forward gradients using forward ad and prototype vmap support. Defaults to ``False``.
  1823. check_forward_ad (bool, optional): if ``True``, check that the gradients computed with forward
  1824. mode AD match the numerical ones. Defaults to ``False``.
  1825. check_backward_ad (bool, optional): if ``False``, do not perform any checks that rely on
  1826. backward mode AD to be implemented. Defaults to ``True``.
  1827. fast_mode (bool, optional): Fast mode for gradcheck and gradgradcheck is currently only
  1828. implemented for R to R functions. If none of the inputs and outputs are complex
  1829. a faster implementation of gradcheck that no longer computes the entire jacobian
  1830. is run; otherwise, we fall back to the slow implementation.
  1831. masked (bool, optional): if ``True``, the gradients of unspecified elements of
  1832. sparse tensors are ignored. Defaults to ``False``.
  1833. Returns:
  1834. ``True`` if all differences satisfy allclose condition
  1835. """
  1836. if not (check_forward_ad or check_backward_ad):
  1837. raise AssertionError(
  1838. "Expected at least one of check_forward_ad or check_backward_ad to be True"
  1839. )
  1840. if check_batched_grad and not check_backward_ad:
  1841. raise AssertionError(
  1842. "Setting check_batched_grad=True requires check_backward_ad to be True"
  1843. )
  1844. if check_batched_forward_grad and not check_forward_ad:
  1845. raise AssertionError(
  1846. "Setting check_batched_forward_grad=True requires check_forward_ad to be True"
  1847. )
  1848. args = locals().copy()
  1849. args.pop("raise_exception")
  1850. if not raise_exception:
  1851. try:
  1852. return _gradcheck_helper(**args)
  1853. except GradcheckError:
  1854. return False
  1855. else:
  1856. return _gradcheck_helper(**args)
  1857. def _gradcheck_helper(
  1858. func,
  1859. inputs,
  1860. eps,
  1861. atol,
  1862. rtol,
  1863. nondet_tol,
  1864. check_undefined_grad,
  1865. check_grad_dtypes,
  1866. check_batched_grad,
  1867. check_batched_forward_grad,
  1868. check_forward_ad,
  1869. check_backward_ad,
  1870. fast_mode,
  1871. masked,
  1872. ):
  1873. tupled_inputs = _as_tuple(inputs)
  1874. _check_inputs(tupled_inputs)
  1875. func_out = func(*tupled_inputs)
  1876. outputs = _differentiable_outputs(func_out)
  1877. _check_outputs(outputs)
  1878. gradcheck_fn = functools.partial(
  1879. _fast_gradcheck if fast_mode else _slow_gradcheck, masked=masked
  1880. )
  1881. _gradcheck_real_imag(
  1882. gradcheck_fn,
  1883. func,
  1884. func_out,
  1885. tupled_inputs,
  1886. outputs,
  1887. eps,
  1888. rtol,
  1889. atol,
  1890. check_grad_dtypes,
  1891. check_forward_ad=check_forward_ad,
  1892. check_backward_ad=check_backward_ad,
  1893. nondet_tol=nondet_tol,
  1894. check_undefined_grad=check_undefined_grad,
  1895. )
  1896. if check_batched_forward_grad:
  1897. _test_batched_grad_forward_ad(func, tupled_inputs)
  1898. # Short circuit because remaining tests rely on backward AD to be implemented
  1899. if not check_backward_ad:
  1900. return True
  1901. for i, o in enumerate(outputs):
  1902. if check_batched_grad:
  1903. _test_batched_grad(tupled_inputs, o, i)
  1904. _test_backward_mul_by_grad_output(outputs, tupled_inputs, masked)
  1905. if check_undefined_grad and check_backward_ad:
  1906. _test_undefined_backward_mode(func, outputs, tupled_inputs)
  1907. return True
  1908. def gradgradcheck(
  1909. func: Callable[..., _TensorOrTensors], # See Note [VarArg of Tensors]
  1910. inputs: _TensorOrTensors,
  1911. grad_outputs: Optional[_TensorOrOptionalTensors] = None,
  1912. *,
  1913. eps: float = 1e-6,
  1914. atol: float = 1e-5,
  1915. rtol: float = 1e-3,
  1916. gen_non_contig_grad_outputs: bool = False,
  1917. raise_exception: bool = True,
  1918. nondet_tol: float = 0.0,
  1919. check_undefined_grad: bool = True,
  1920. check_grad_dtypes: bool = False,
  1921. check_batched_grad: bool = False,
  1922. check_fwd_over_rev: bool = False,
  1923. check_rev_over_rev: bool = True,
  1924. fast_mode: bool = False,
  1925. masked: bool = False,
  1926. ) -> bool: # noqa: D400,D205
  1927. r"""Check gradients of gradients computed via small finite differences
  1928. against analytical gradients wrt tensors in :attr:`inputs` and
  1929. :attr:`grad_outputs` that are of floating point or complex type and with
  1930. ``requires_grad=True``.
  1931. This function checks that backpropagating through the gradients computed
  1932. to the given :attr:`grad_outputs` are correct.
  1933. The check between numerical and analytical gradients uses :func:`~torch.allclose`.
  1934. .. note::
  1935. The default values are designed for :attr:`input` and
  1936. :attr:`grad_outputs` of double precision. This check will likely fail if
  1937. they are of less precision, e.g., ``FloatTensor``.
  1938. .. warning::
  1939. If any checked tensor in :attr:`input` and :attr:`grad_outputs` has
  1940. overlapping memory, i.e., different indices pointing to the same memory
  1941. address (e.g., from :func:`torch.Tensor.expand`), this check will likely fail
  1942. because the numerical gradients computed by point perturbation at such
  1943. indices will change values at all other indices that share the same
  1944. memory address.
  1945. Args:
  1946. func (function): a Python function that takes Tensor inputs and returns
  1947. a Tensor or a tuple of Tensors
  1948. inputs (tuple of Tensor or Tensor): inputs to the function
  1949. grad_outputs (tuple of [Tensor or None] or Tensor, optional): The gradients with
  1950. respect to the function's outputs.
  1951. eps (float, optional): perturbation for finite differences
  1952. atol (float, optional): absolute tolerance
  1953. rtol (float, optional): relative tolerance
  1954. gen_non_contig_grad_outputs (bool, optional): if :attr:`grad_outputs` is
  1955. ``None`` and :attr:`gen_non_contig_grad_outputs` is ``True``, the
  1956. randomly generated gradient outputs are made to be noncontiguous
  1957. raise_exception (bool, optional): indicating whether to raise an exception if
  1958. the check fails. The exception gives more information about the
  1959. exact nature of the failure. This is helpful when debugging gradchecks.
  1960. nondet_tol (float, optional): tolerance for non-determinism. When running
  1961. identical inputs through the differentiation, the results must either match
  1962. exactly (default, 0.0) or be within this tolerance. Note that a small amount
  1963. of nondeterminism in the gradient will lead to larger inaccuracies in
  1964. the second derivative.
  1965. check_undefined_grad (bool, optional): if True, check if undefined output grads
  1966. are supported and treated as zeros
  1967. check_batched_grad (bool, optional): if True, check if we can compute
  1968. batched gradients using prototype vmap support. Defaults to False.
  1969. fast_mode (bool, optional): if True, run a faster implementation of gradgradcheck that
  1970. no longer computes the entire jacobian.
  1971. masked (bool, optional): if True, the gradients of unspecified elements of
  1972. sparse tensors are ignored (default, False).
  1973. Returns:
  1974. True if all differences satisfy allclose condition
  1975. """
  1976. if not (check_fwd_over_rev or check_rev_over_rev):
  1977. raise AssertionError(
  1978. "Expected at least one of check_fwd_over_rev or check_rev_over_rev to be True"
  1979. )
  1980. if check_undefined_grad and not check_rev_over_rev:
  1981. raise AssertionError(
  1982. "Setting check_undefined_grad=True requires check_rev_over_rev to be True"
  1983. )
  1984. if check_batched_grad and not check_rev_over_rev:
  1985. raise AssertionError(
  1986. "Setting check_batched_grad=True requires check_rev_over_rev to be True"
  1987. )
  1988. # TODO: do we want to test this too?
  1989. # assert not (check_batched_forward_grad and not check_fwd_over_rev), (
  1990. # "Setting check_batched_forward_grad=True requires check_fwd_over_rev to be True")
  1991. tupled_inputs = _as_tuple(inputs)
  1992. if grad_outputs is None:
  1993. # If grad_outputs is not specified, create random Tensors of the same shape, type, and device as the outputs
  1994. outputs = _differentiable_outputs(func(*tupled_inputs))
  1995. tupled_grad_outputs = tuple(
  1996. torch.testing.make_tensor(
  1997. x.shape,
  1998. dtype=x.dtype
  1999. if x.is_floating_point() or x.is_complex()
  2000. else torch.double,
  2001. device=x.device,
  2002. low=-1,
  2003. high=1,
  2004. requires_grad=True,
  2005. noncontiguous=gen_non_contig_grad_outputs,
  2006. )
  2007. for x in outputs
  2008. )
  2009. else:
  2010. tupled_grad_outputs = _as_tuple(grad_outputs)
  2011. num_outputs = len(tupled_grad_outputs)
  2012. # NB: We need to save the requires_grad information about the inputs here because gradcheck detaches inputs
  2013. # before running forward mode AD
  2014. diff_input_args_indices = {
  2015. i for i, x in enumerate(tupled_inputs) if is_tensor_like(x) and x.requires_grad
  2016. }
  2017. diff_grad_output_indices = {
  2018. i for i, x in enumerate(tupled_grad_outputs) if x.requires_grad
  2019. }
  2020. def new_func(*args):
  2021. # Restore the requires_grad information
  2022. input_args = tuple(
  2023. x.requires_grad_() if i in diff_input_args_indices else x
  2024. for i, x in enumerate(args[:-num_outputs])
  2025. )
  2026. outputs = _differentiable_outputs(func(*input_args))
  2027. grad_outputs = tuple(
  2028. x.requires_grad_() if i in diff_grad_output_indices else x
  2029. for i, x in enumerate(args[-num_outputs:])
  2030. )
  2031. diff_input_args = tuple(
  2032. x for i, x in enumerate(input_args) if i in diff_input_args_indices
  2033. )
  2034. grad_inputs = torch.autograd.grad(
  2035. outputs, diff_input_args, grad_outputs, create_graph=True, allow_unused=True
  2036. )
  2037. grad_inputs = tuple(g for g in grad_inputs if g is not None)
  2038. return grad_inputs
  2039. return gradcheck(
  2040. new_func,
  2041. tupled_inputs + tupled_grad_outputs,
  2042. eps=eps,
  2043. atol=atol,
  2044. rtol=rtol,
  2045. raise_exception=raise_exception,
  2046. nondet_tol=nondet_tol,
  2047. check_undefined_grad=check_undefined_grad,
  2048. check_grad_dtypes=check_grad_dtypes,
  2049. check_batched_grad=check_batched_grad,
  2050. fast_mode=fast_mode,
  2051. check_forward_ad=check_fwd_over_rev,
  2052. check_backward_ad=check_rev_over_rev,
  2053. masked=masked,
  2054. )