gradcheck.py 88 KB

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