gradcheck.py 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. import torch
  2. from torch.types import _TensorOrTensors
  3. import torch.testing
  4. from torch.overrides import is_tensor_like
  5. import collections
  6. from itertools import product
  7. import warnings
  8. from typing import Callable, Union, Optional, Iterable, List, Tuple, Dict
  9. from torch._vmap_internals import vmap, _vmap
  10. import functools
  11. # Note: `get_*_jacobian` functions are added here even though we didn't intend to make them public
  12. # since they have been exposed from before we added `__all__` and we already maintain BC for them
  13. # We should eventually deprecate them and remove them from `__all__`
  14. __all__ = ["gradcheck", "gradgradcheck", "GradcheckError", "get_numerical_jacobian",
  15. "get_analytical_jacobian", "get_numerical_jacobian_wrt_specific_input"]
  16. class GradcheckError(RuntimeError):
  17. r"""Error raised by :func:`gradcheck` and :func:`gradgradcheck`"""
  18. pass
  19. def _is_sparse_compressed_tensor(obj: torch.Tensor):
  20. return obj.layout in {torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc}
  21. def _is_sparse_any_tensor(obj: torch.Tensor):
  22. return _is_sparse_compressed_tensor(obj) or obj.layout is torch.sparse_coo
  23. def _is_float_or_complex_tensor(obj):
  24. return is_tensor_like(obj) and (obj.is_floating_point() or obj.is_complex())
  25. def _allocate_jacobians_with_inputs(input_tensors: Tuple, numel_output) -> Tuple[torch.Tensor, ...]:
  26. # Makes zero-filled tensors from inputs. If `numel_output` is not None, for
  27. # each tensor in `input_tensors`, returns a new zero-filled tensor with height
  28. # of `t.numel` and width of `numel_output`. Otherwise, for each tensor, returns
  29. # a 1-d tensor with size `(t.numel,)`. Each new tensor will be strided and have
  30. # the same dtype and device as those of the corresponding input.
  31. out: List[torch.Tensor] = []
  32. for t in input_tensors:
  33. if _is_float_or_complex_tensor(t) and t.requires_grad:
  34. out.append(t.new_zeros((t.numel(), numel_output), layout=torch.strided))
  35. return tuple(out)
  36. def _allocate_jacobians_with_outputs(output_tensors: Tuple, numel_input, dtype=None,
  37. device=None) -> Tuple[torch.Tensor, ...]:
  38. # Makes zero-filled tensors from outputs. If `dim` is not None, for each tensor
  39. # in `output_tensors`, returns a new zero-filled tensor with height of `dim` and
  40. # width of `t.numel`. Otherwise, for each tensor, returns a 1-d tensor with size
  41. # (t.numel,).
  42. out: List[torch.Tensor] = []
  43. options = {"dtype": dtype, "device": device, "layout": torch.strided}
  44. for t in output_tensors:
  45. if _is_float_or_complex_tensor(t):
  46. out.append(t.new_zeros((numel_input, t.numel()), **options))
  47. return tuple(out)
  48. def _iter_tensors(x: Union[torch.Tensor, Iterable[torch.Tensor]],
  49. only_requiring_grad: bool = False) -> Iterable[torch.Tensor]:
  50. if is_tensor_like(x):
  51. # mypy doesn't narrow type of `x` to torch.Tensor
  52. if x.requires_grad or not only_requiring_grad: # type: ignore[union-attr]
  53. yield x # type: ignore[misc]
  54. elif isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
  55. for elem in x:
  56. for result in _iter_tensors(elem, only_requiring_grad):
  57. yield result
  58. def _iter_tensor(x_tensor):
  59. # (Only used for slow gradcheck) Returns a generator that yields the following
  60. # elements at each iteration:
  61. # 1) a tensor: the same tensor is returned across all iterations. The tensor
  62. # is not the same as the original x_tensor as given as input - it is
  63. # prepared so that it can be modified in-place. Depending on whether the
  64. # input tensor is strided, sparse, or dense, the returned tensor may or may
  65. # not share storage with x_tensor.
  66. # 2) a tuple of indices that can be used with advanced indexing (yielded in
  67. # dictionary order)
  68. # 3) flattened index that will be used to index into the Jacobian tensor
  69. #
  70. # For a tensor t with size (2, 2), _iter_tensor yields:
  71. # `x, (0, 0), 0`, `x, (0, 1), 1`, `x, (1, 0), 2`, `x, (1, 1), 3`
  72. #
  73. # where x is the t.data of the original tensor. Perturbing the entry of x
  74. # at index (1, 1) yields the 3rd column of the overall Jacobian matrix.
  75. if _is_sparse_any_tensor(x_tensor):
  76. def get_stride(size):
  77. dim = len(size)
  78. tmp = 1
  79. stride = [0] * dim
  80. for i in reversed(range(dim)):
  81. stride[i] = tmp
  82. tmp *= size[i]
  83. return stride
  84. x_nnz = x_tensor._nnz()
  85. x_size = list(x_tensor.size())
  86. if x_tensor.layout is torch.sparse_coo:
  87. x_indices = x_tensor._indices().t()
  88. x_values = x_tensor._values()
  89. elif x_tensor.layout is torch.sparse_csr:
  90. x_indices = torch._convert_indices_from_csr_to_coo(x_tensor.crow_indices(), x_tensor.col_indices()).t()
  91. x_values = x_tensor.values()
  92. elif x_tensor.layout is torch.sparse_csc:
  93. x_indices = torch._convert_indices_from_csr_to_coo(x_tensor.ccol_indices(), x_tensor.row_indices(), transpose=True).t()
  94. x_values = x_tensor.values()
  95. elif x_tensor.layout is torch.sparse_bsr:
  96. x_block_values = x_tensor.values()
  97. x_blocksize = x_block_values.size()[1:3]
  98. x_indices = torch._convert_indices_from_csr_to_coo(x_tensor.crow_indices(), x_tensor.col_indices()) \
  99. .repeat_interleave(x_blocksize[0] * x_blocksize[1], 1) \
  100. .mul_(torch.tensor(x_blocksize).reshape(2, 1)) \
  101. .add_(torch.stack(torch.where(torch.ones(x_blocksize))).repeat(1, x_nnz)).t()
  102. x_values = x_block_values.flatten(0, 2)
  103. x_nnz = x_values.size(0)
  104. elif x_tensor.layout is torch.sparse_bsc:
  105. x_block_values = x_tensor.values()
  106. x_blocksize = x_block_values.size()[1:3]
  107. x_indices = torch._convert_indices_from_csr_to_coo(x_tensor.ccol_indices(), x_tensor.row_indices(), transpose=True) \
  108. .repeat_interleave(x_blocksize[0] * x_blocksize[1], 1) \
  109. .mul_(torch.tensor(x_blocksize).reshape(2, 1)) \
  110. .add_(torch.stack(torch.where(torch.ones(x_blocksize))).repeat(1, x_nnz)).t()
  111. x_values = x_block_values.flatten(0, 2)
  112. x_nnz = x_values.size(0)
  113. else:
  114. raise NotImplementedError(f'_iter_tensor for {x_tensor.layout} input')
  115. x_stride = get_stride(x_size)
  116. # Use .data here to get around the version check
  117. x_values = x_values.data
  118. for i in range(x_nnz):
  119. x_value = x_values[i]
  120. for x_idx in product(*[range(m) for m in x_values.size()[1:]]):
  121. indices = x_indices[i].tolist() + list(x_idx)
  122. d_idx = sum(indices[k] * x_stride[k] for k in range(len(x_size)))
  123. yield x_value, x_idx, d_idx
  124. elif x_tensor.layout == torch._mkldnn: # type: ignore[attr-defined]
  125. for d_idx, x_idx in enumerate(product(*[range(m) for m in x_tensor.size()])):
  126. # this is really inefficient, but without indexing implemented, there's
  127. # not really a better way than converting back and forth
  128. x_tensor_dense = x_tensor.to_dense()
  129. yield x_tensor_dense, x_idx, d_idx
  130. else:
  131. # Use .data here to get around the version check
  132. x_tensor = x_tensor.data
  133. for d_idx, x_idx in enumerate(product(*[range(m) for m in x_tensor.size()])):
  134. yield x_tensor, x_idx, d_idx
  135. def _get_numerical_jacobian(fn, inputs, outputs=None, target=None, eps=1e-3,
  136. is_forward_ad=False) -> List[Tuple[torch.Tensor, ...]]:
  137. """Computes the numerical Jacobian of `fn(inputs)` with respect to `target`. If
  138. not specified, targets are the input. Returns M * N Jacobians where N is the
  139. number of tensors in target that require grad and M is the number of non-integral
  140. outputs.
  141. Args:
  142. fn: the function to compute the jacobian for
  143. inputs: inputs to `fn`
  144. outputs: provide precomputed outputs to avoid one extra invocation of fn
  145. target: the Tensors wrt whom Jacobians are calculated (default=`inputs`)
  146. eps: the magnitude of the perturbation during finite differencing
  147. (default=`1e-3`)
  148. is_forward_ad: if this numerical jacobian is computed to be checked wrt
  149. forward AD gradients (this is used for error checking only)
  150. Returns:
  151. A list of M N-tuples of tensors
  152. Note that `target` may not even be part of `input` to `fn`, so please be
  153. **very careful** in this to not clone `target`.
  154. """
  155. jacobians: List[Tuple[torch.Tensor, ...]] = []
  156. if outputs is None:
  157. outputs = _as_tuple(fn(*_as_tuple(inputs)))
  158. if not is_forward_ad and any(o.is_complex() for o in outputs):
  159. raise ValueError("Expected output to be non-complex. get_numerical_jacobian no "
  160. "longer supports functions that return complex outputs.")
  161. if target is None:
  162. target = inputs
  163. inp_indices = [i for i, a in enumerate(target) if is_tensor_like(a) and a.requires_grad]
  164. for i, (inp, inp_idx) in enumerate(zip(_iter_tensors(target, True), inp_indices)):
  165. jacobians += [get_numerical_jacobian_wrt_specific_input(fn, inp_idx, inputs, outputs, eps,
  166. input=inp, is_forward_ad=is_forward_ad)]
  167. return jacobians
  168. def get_numerical_jacobian(fn, inputs, target=None, eps=1e-3, grad_out=1.0):
  169. """Deprecated API to compute the numerical Jacobian for a given fn and its inputs.
  170. Args:
  171. fn: the function to compute the Jacobian for (must take inputs as a tuple)
  172. input: input to `fn`
  173. target: the Tensors wrt whom Jacobians are calculated (default=`input`)
  174. eps: the magnitude of the perturbation during finite differencing
  175. (default=`1e-3`)
  176. Returns:
  177. A list of Jacobians of `fn` (restricted to its first output) with respect to
  178. each input or target, if provided.
  179. Note that `target` may not even be part of `input` to `fn`, so please be
  180. **very careful** in this to not clone `target`.
  181. """
  182. warnings.warn("get_numerical_jacobian was part of PyTorch's private API and not "
  183. "meant to be exposed. We are deprecating it and it will be removed "
  184. "in a future version of PyTorch. If you have a specific use for "
  185. "this or feature request for this to be a stable API, please file "
  186. "us an issue at https://github.com/pytorch/pytorch/issues/new")
  187. if grad_out != 1.0: # grad_out param is only kept for backward compatibility reasons
  188. raise ValueError("Expected grad_out to be 1.0. get_numerical_jacobian no longer "
  189. "supports values of grad_out != 1.0.")
  190. def fn_pack_inps(*inps):
  191. return fn(inps)
  192. jacobians = _get_numerical_jacobian(fn_pack_inps, inputs, None, target, eps)
  193. return tuple(jacobian_for_each_output[0] for jacobian_for_each_output in jacobians)
  194. def _compute_numerical_gradient(fn, entry, v, norm_v, nbhd_checks_fn):
  195. # Performs finite differencing by perturbing `entry` in-place by `v` and
  196. # returns the gradient of each of the outputs wrt to x at idx.
  197. orig = entry.clone()
  198. entry.copy_(orig - v)
  199. outa = fn()
  200. entry.copy_(orig + v)
  201. outb = fn()
  202. entry.copy_(orig)
  203. def compute(a, b):
  204. nbhd_checks_fn(a, b)
  205. ret = (b - a) / (2 * norm_v)
  206. return ret.detach().reshape(-1)
  207. return tuple(compute(a, b) for (a, b) in zip(outa, outb))
  208. def _compute_numerical_jvps_wrt_specific_input(jvp_fn, delta, input_is_complex,
  209. is_forward_ad=False) -> List[torch.Tensor]:
  210. # Computing the jacobian only works for real delta
  211. # For details on the algorithm used here, refer:
  212. # Section 3.5.3 https://arxiv.org/pdf/1701.00392.pdf
  213. # s = fn(z) where z = x for real valued input
  214. # and z = x + yj for complex valued input
  215. jvps: List[torch.Tensor] = []
  216. ds_dx_tup = jvp_fn(delta[0] if isinstance(delta, tuple) else delta)
  217. if input_is_complex: # C -> R
  218. ds_dy_tup = jvp_fn(delta[1] * 1j) if isinstance(delta, tuple) else jvp_fn(delta * 1j)
  219. for ds_dx, ds_dy in zip(ds_dx_tup, ds_dy_tup):
  220. assert(not ds_dx.is_complex())
  221. # conjugate wirtinger derivative
  222. conj_w_d = ds_dx + ds_dy * 1j
  223. jvps.append(conj_w_d)
  224. else:
  225. for ds_dx in ds_dx_tup: # R -> R or (R -> C for the forward AD case)
  226. assert(is_forward_ad or not ds_dx.is_complex())
  227. jvps.append(ds_dx)
  228. return jvps
  229. def _combine_jacobian_cols(jacobians_cols: Dict[int, List[torch.Tensor]], outputs, input,
  230. numel) -> Tuple[torch.Tensor, ...]:
  231. # jacobian_cols maps column_idx -> output_idx -> single column of jacobian Tensor
  232. # we return a list that maps output_idx -> full jacobian Tensor
  233. jacobians = _allocate_jacobians_with_outputs(outputs, numel, dtype=input.dtype if input.dtype.is_complex else None)
  234. for i, jacobian in enumerate(jacobians):
  235. for k, v in jacobians_cols.items():
  236. jacobian[k] = v[i]
  237. return jacobians
  238. def _prepare_input(input: torch.Tensor, maybe_perturbed_input: Optional[torch.Tensor],
  239. fast_mode=False) -> torch.Tensor:
  240. # Prepares the inputs to be passed into the function while including the new
  241. # modified input.
  242. if input.layout == torch._mkldnn: # type: ignore[attr-defined] # no attr _mkldnn
  243. # Convert back to mkldnn
  244. if maybe_perturbed_input is not None:
  245. return maybe_perturbed_input.to_mkldnn()
  246. else:
  247. return input
  248. elif _is_sparse_any_tensor(input):
  249. if fast_mode and maybe_perturbed_input is not None:
  250. # entry is already a "cloned" version of the original tensor
  251. # thus changes to entry are not reflected in the input
  252. return maybe_perturbed_input
  253. else:
  254. return input
  255. else:
  256. # We cannot use entry (input.data) if we want gradgrad to work because
  257. # fn (in the gradgrad case) needs to compute grad wrt input
  258. return input
  259. def _check_outputs_same_dtype_and_shape(output1, output2, eps, idx=None) -> None:
  260. # Check that the returned outputs don't have different dtype or shape when you
  261. # perturb the input
  262. on_index = "on index {idx} " if idx is not None else ""
  263. assert output1.shape == output2.shape, \
  264. (f"Expected `func` to return outputs with the same shape"
  265. f" when inputs are perturbed {on_index}by {eps}, but got:"
  266. f" shapes {output1.shape} and {output2.shape}.")
  267. assert output1.dtype == output2.dtype, \
  268. (f"Expected `func` to return outputs with the same dtype"
  269. f" when inputs are perturbed {on_index}by {eps}, but got:"
  270. f" dtypes {output1.dtype} and {output2.dtype}.")
  271. def get_numerical_jacobian_wrt_specific_input(fn, input_idx, inputs, outputs, eps,
  272. input=None, is_forward_ad=False) -> Tuple[torch.Tensor, ...]:
  273. # Computes the numerical jacobians wrt to a single input. Returns N jacobian
  274. # tensors, where N is the number of outputs. We use a dictionary for
  275. # jacobian_cols because indices aren't necessarily consecutive for sparse inputs
  276. # When we perturb only a single element of the input tensor at a time, the jvp
  277. # is equivalent to a single col of the Jacobian matrix of fn.
  278. jacobian_cols: Dict[int, List[torch.Tensor]] = {}
  279. input = inputs[input_idx] if input is None else input
  280. assert input.requires_grad
  281. for x, idx, d_idx in _iter_tensor(input):
  282. wrapped_fn = _with_prepare_inputs(fn, inputs, input_idx, x)
  283. input_to_perturb = x[idx]
  284. nbhd_checks_fn = functools.partial(_check_outputs_same_dtype_and_shape, idx=idx, eps=eps)
  285. jvp_fn = _get_numerical_jvp_fn(wrapped_fn, input_to_perturb, eps, nbhd_checks_fn)
  286. jacobian_cols[d_idx] = _compute_numerical_jvps_wrt_specific_input(jvp_fn, eps, x.is_complex(), is_forward_ad)
  287. return _combine_jacobian_cols(jacobian_cols, outputs, input, input.numel())
  288. def _get_analytical_jacobian_forward_ad(fn, inputs, outputs, *, check_grad_dtypes=False,
  289. all_u=None) -> Tuple[Tuple[torch.Tensor, ...], ...]:
  290. """Computes the analytical Jacobian using forward mode AD of `fn(inputs)` using forward mode AD with respect
  291. to `target`. Returns N * M Jacobians where N is the number of tensors in target that require grad and
  292. M is the number of non-integral outputs.
  293. Contrary to other functions here, this function requires "inputs" to actually be used by the function.
  294. The computed value is expected to be wrong if the function captures the inputs by side effect instead of
  295. using the passed ones (many torch.nn tests do this).
  296. Args:
  297. fn: the function to compute the jacobian for
  298. inputs: inputs to `fn`
  299. outputs: provide precomputed outputs to avoid one extra invocation of fn
  300. check_grad_dtypes: if True, will check that the gradient dtype are valid
  301. all_u (optional): if provided, the Jacobian will be right multiplied with this vector
  302. Returns:
  303. A tuple of M N-tuples of tensors
  304. """
  305. # To avoid early import issues
  306. fwAD = torch.autograd.forward_ad
  307. tensor_inputs = tuple(i for i in inputs if is_tensor_like(i) and i.requires_grad)
  308. if any(i.is_complex() for i in tensor_inputs):
  309. raise ValueError("Expected inputs to be non-complex for _get_analytical_jacobian_forward_ad.")
  310. if all_u:
  311. jacobians = tuple(_allocate_jacobians_with_outputs(outputs, 1) for i in tensor_inputs)
  312. else:
  313. jacobians = tuple(_allocate_jacobians_with_outputs(outputs, i.numel()) for i in tensor_inputs)
  314. with fwAD.dual_level():
  315. fw_grads = []
  316. dual_inputs = []
  317. for i, inp in enumerate(inputs):
  318. if is_tensor_like(inp) and inp.requires_grad:
  319. if inp.layout == torch._mkldnn: # type: ignore[attr-defined]
  320. raise ValueError("MKLDNN inputs are not support for forward AD gradcheck.")
  321. inp = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  322. # If inp is a differentiable view, the dual might not be the tangent given to
  323. # make_dual, so read it explicitly from the dual tensor
  324. fw_grads.append(fwAD.unpack_dual(inp)[1])
  325. dual_inputs.append(inp)
  326. if all_u:
  327. # Do the full reduction in one pass
  328. # To be consistent with numerical evaluation, we actually compute one reduction per input
  329. for i, (fw_grad, u) in enumerate(zip(fw_grads, all_u)):
  330. fw_grad.copy_(u.view_as(fw_grad))
  331. raw_outputs = _as_tuple(fn(*dual_inputs))
  332. dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs)
  333. for index_o, d_o in enumerate(dual_outputs):
  334. val, res = fwAD.unpack_dual(d_o)
  335. if check_grad_dtypes and res is not None and val.is_complex() != res.is_complex():
  336. raise GradcheckError('Forward AD gradient has dtype mismatch.')
  337. # Remove extra dimension of size 1 corresponding to the reduced input
  338. jacobians[i][index_o].squeeze_(0)
  339. if res is None:
  340. jacobians[i][index_o].zero_()
  341. else:
  342. jacobians[i][index_o].copy_(res.reshape(-1))
  343. fw_grad.zero_()
  344. else:
  345. # Reconstruct the full Jacobian column by column
  346. for i, fw_grad in enumerate(fw_grads):
  347. for lin_idx, grad_idx in enumerate(product(*[range(m) for m in fw_grad.size()])):
  348. fw_grad[grad_idx] = 1.
  349. raw_outputs = _as_tuple(fn(*dual_inputs))
  350. dual_outputs = filter(_is_float_or_complex_tensor, raw_outputs)
  351. for index_o, d_o in enumerate(dual_outputs):
  352. val, res = fwAD.unpack_dual(d_o)
  353. if check_grad_dtypes and res is not None and val.is_complex() != res.is_complex():
  354. raise GradcheckError('Forward AD gradient has dtype mismatch.')
  355. if res is None:
  356. jacobians[i][index_o][lin_idx].zero_()
  357. else:
  358. jacobians[i][index_o][lin_idx].copy_(res.reshape(-1))
  359. fw_grad[grad_idx] = 0.
  360. return jacobians
  361. def _get_input_to_perturb(input):
  362. # Prepare the input so that it can be modified in-place and do certain
  363. # operations that require the tensor to have strides. If fast_mode=False,
  364. # _iter_tensor would handle the below cases:
  365. if input.layout == torch._mkldnn: # type: ignore[attr-defined] # no attr _mkldnn
  366. # Convert to dense so we can perform operations that require strided tensors
  367. input_to_perturb = input.to_dense()
  368. elif _is_sparse_any_tensor(input):
  369. # Clone because input may require grad, and copy_ calls resize_,
  370. # which is not allowed for .data
  371. input_to_perturb = input.clone()
  372. else:
  373. input_to_perturb = input.data
  374. return input_to_perturb
  375. def _with_prepare_inputs(fn, inputs, input_idx, input_to_perturb, fast_mode=False):
  376. # Wraps `fn` so that its inputs are already supplied
  377. def wrapped_fn():
  378. inp = tuple(_prepare_input(a, input_to_perturb if i == input_idx else None, fast_mode)
  379. if is_tensor_like(a) else a for i, a in enumerate(_as_tuple(inputs)))
  380. return tuple(a.clone() for a in _as_tuple(fn(*inp)))
  381. return wrapped_fn
  382. def _get_numerical_jvp_fn(wrapped_fn, input_to_perturb, eps, nbhd_checks_fn):
  383. # Wraps jvp_fn so that certain arguments are already supplied
  384. def jvp_fn(delta):
  385. return _compute_numerical_gradient(wrapped_fn, input_to_perturb, delta, eps, nbhd_checks_fn)
  386. return jvp_fn
  387. def _reshape_tensor_or_tuple(u, shape):
  388. # We don't need to reshape when input corresponding to u is sparse
  389. if isinstance(u, tuple):
  390. if not _is_sparse_any_tensor(u[0]):
  391. return (u[0].reshape(shape), u[1].reshape(shape))
  392. else:
  393. if not _is_sparse_any_tensor(u):
  394. return u.reshape(shape)
  395. return u
  396. def _mul_tensor_or_tuple(u, k):
  397. if isinstance(u, tuple):
  398. return (k * u[0], k * u[1])
  399. else:
  400. return k * u
  401. def _get_numerical_jvp_wrt_specific_input(fn, input_idx, inputs, u, eps, is_forward_ad=False) -> List[torch.Tensor]:
  402. input = inputs[input_idx]
  403. input_to_perturb = _get_input_to_perturb(input)
  404. wrapped_fn = _with_prepare_inputs(fn, inputs, input_idx, input_to_perturb, True)
  405. nbhd_checks_fn = functools.partial(_check_outputs_same_dtype_and_shape, eps=eps)
  406. jvp_fn = _get_numerical_jvp_fn(wrapped_fn, input_to_perturb, eps, nbhd_checks_fn)
  407. u = _reshape_tensor_or_tuple(u, input_to_perturb.shape)
  408. u = _mul_tensor_or_tuple(u, eps)
  409. return _compute_numerical_jvps_wrt_specific_input(jvp_fn, u, input.is_complex(), is_forward_ad)
  410. def _get_numerical_vJu(fn, inputs, inp_indices, func_out, all_u, all_v, eps, is_forward_ad):
  411. # Note that all_v can also be None, in that case, this function only computes Ju.
  412. reduced_jacobians: List[List[torch.Tensor]] = []
  413. for i, (inp_idx, u) in enumerate(zip(inp_indices, all_u)):
  414. all_Ju = _get_numerical_jvp_wrt_specific_input(fn, inp_idx, inputs, u, eps, is_forward_ad)
  415. # Filter out the Ju for non floating point outputs
  416. filtered_Ju = []
  417. func_out = _as_tuple(func_out)
  418. assert len(all_Ju) == len(func_out)
  419. for Ju, output in zip(all_Ju, func_out):
  420. if _is_float_or_complex_tensor(output):
  421. filtered_Ju.append(Ju)
  422. else:
  423. # TODO: handle the other Ju
  424. pass
  425. if all_v is not None:
  426. jacobian_scalars: List[torch.Tensor] = []
  427. for v, Ju in zip(all_v, filtered_Ju):
  428. jacobian_scalars.append(_dot_with_type_promotion(v, Ju))
  429. reduced_jacobians.append(jacobian_scalars)
  430. else:
  431. reduced_jacobians.append(filtered_Ju)
  432. return reduced_jacobians
  433. def _check_jacobians_equal(j1, j2, atol):
  434. # Check whether the max difference between two Jacobian tensors are within some
  435. # tolerance `atol`.
  436. for j1_x, j2_x in zip(j1, j2):
  437. if j1_x.numel() != 0 and (j1_x - j2_x).abs().max() > atol:
  438. return False
  439. return True
  440. def _stack_and_check_tensors(list_of_list_of_tensors, inputs,
  441. numel_outputs) -> Tuple[Tuple[torch.Tensor, ...], bool, bool]:
  442. # For the ith tensor in the inner list checks whether it has the same size and
  443. # dtype as the ith differentiable input.
  444. out_jacobians = _allocate_jacobians_with_inputs(inputs, numel_outputs)
  445. diff_input_list = list(_iter_tensors(inputs, True))
  446. correct_grad_sizes = True
  447. correct_grad_types = True
  448. for i, tensor_list in enumerate(list_of_list_of_tensors):
  449. inp = diff_input_list[i]
  450. out_jacobian = out_jacobians[i]
  451. for j, tensor in enumerate(tensor_list):
  452. if tensor is not None and tensor.size() != inp.size():
  453. correct_grad_sizes = False
  454. elif tensor is not None and tensor.dtype != inp.dtype:
  455. correct_grad_types = False
  456. if tensor is None:
  457. out_jacobian[:, j].zero_()
  458. else:
  459. dense = tensor.to_dense() if not tensor.layout == torch.strided else tensor
  460. assert out_jacobian[:, j].numel() == dense.numel()
  461. out_jacobian[:, j] = dense.reshape(-1)
  462. return out_jacobians, correct_grad_sizes, correct_grad_types
  463. FAILED_NONDET_MSG = """\n
  464. NOTE: If your op relies on non-deterministic operations i.e., it is listed here:
  465. https://pytorch.org/docs/stable/generated/torch.use_deterministic_algorithms.html
  466. this failure might be expected.
  467. If you are adding a new operator, please file an issue and then use one of the
  468. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  469. If the test
  470. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  471. with `nondet_tol=<tol>` as a keyword argument.
  472. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  473. to have `gradcheck_nondet_tol=<tol>`.
  474. - is a Module test (e.g., in common_nn.py), then modify the corresponding
  475. module_test entry to have `gradcheck_nondet_tol=<tol>`
  476. """
  477. def _check_analytical_jacobian_attributes(inputs, output, nondet_tol, check_grad_dtypes,
  478. fast_mode=False, v=None) -> Tuple[torch.Tensor, ...]:
  479. # This is used by both fast and slow mode:
  480. # - For slow mode, vjps[i][j] is the jth row the Jacobian wrt the ith
  481. # input.
  482. # - For fast mode, vjps[i][0] is a linear combination of the rows
  483. # of the Jacobian wrt the ith input
  484. diff_input_list = list(_iter_tensors(inputs, True))
  485. def vjp_fn(grad_output):
  486. return torch.autograd.grad(output, diff_input_list, grad_output,
  487. retain_graph=True, allow_unused=True)
  488. # Compute everything twice to check for nondeterminism (which we call reentrancy)
  489. if fast_mode:
  490. vjps1 = _get_analytical_vjps_wrt_specific_output(vjp_fn, output.clone(), v)
  491. vjps2 = _get_analytical_vjps_wrt_specific_output(vjp_fn, output.clone(), v)
  492. else:
  493. vjps1 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  494. vjps2 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  495. output_numel = output.numel() if not fast_mode else 1
  496. jacobians1, types_ok, sizes_ok = _stack_and_check_tensors(vjps1, inputs, output_numel)
  497. jacobians2, _, _ = _stack_and_check_tensors(vjps2, inputs, output_numel)
  498. reentrant = _check_jacobians_equal(jacobians1, jacobians2, nondet_tol)
  499. if not types_ok and check_grad_dtypes:
  500. raise GradcheckError('Gradient has dtype mismatch')
  501. if not sizes_ok:
  502. raise GradcheckError('Analytical gradient has incorrect size')
  503. if not reentrant:
  504. raise GradcheckError('Backward is not reentrant, i.e., running backward with '
  505. 'same input and grad_output multiple times gives different values, '
  506. 'although analytical gradient matches numerical gradient.'
  507. f'The tolerance for nondeterminism was {nondet_tol}.' +
  508. FAILED_NONDET_MSG)
  509. return jacobians1
  510. def _get_analytical_vJu_backward_mode(inputs, outputs, nondet_tol, check_grad_dtypes, all_v, all_u):
  511. reduced_jacobians: List[List[torch.Tensor]] = []
  512. for output, v in zip(outputs, all_v):
  513. all_vJ = _check_analytical_jacobian_attributes(inputs, output, nondet_tol, check_grad_dtypes,
  514. fast_mode=True, v=v)
  515. jacobian_scalars: List[torch.Tensor] = []
  516. for vJ, u in zip(all_vJ, all_u):
  517. # Why do we need squeeze here? vJ is a 2-d tensor so that we can reuse
  518. # the error checking logic from slow mode
  519. vJ = vJ.T.squeeze(0)
  520. if vJ.is_complex(): # C -> R
  521. tv = torch.view_as_real(vJ.resolve_conj())
  522. tr = tv.select(-1, 0)
  523. ti = tv.select(-1, 1)
  524. jacobian_scalars.append(tr.dot(u[0]) + 1j * ti.dot(u[1]))
  525. else: # R -> R
  526. jacobian_scalars.append(vJ.dot(u))
  527. reduced_jacobians.append(jacobian_scalars)
  528. return reduced_jacobians
  529. def get_analytical_jacobian(inputs, output, nondet_tol=0.0, grad_out=1.0):
  530. # Replicates the behavior of the old get_analytical_jacobian before the refactor
  531. # This shares much of its code with _check_analytical_jacobian_attributes
  532. warnings.warn("get_analytical_jacobian was part of PyTorch's private API and not "
  533. "meant to be exposed. We are deprecating it and it will be removed "
  534. "in a future version of PyTorch. If you have a specific use for "
  535. "this or feature request for this to be a stable API, please file "
  536. "us an issue at https://github.com/pytorch/pytorch/issues/new")
  537. if grad_out != 1.0: # grad_out param is only kept for backward compatibility reasons
  538. raise ValueError("Expected grad_out to be 1.0. get_analytical_jacobian no longer "
  539. "supports values of grad_out != 1.0.")
  540. if output.is_complex():
  541. raise ValueError("Expected output to be non-complex. get_analytical_jacobian no "
  542. "longer supports functions that return complex outputs.")
  543. diff_input_list = list(_iter_tensors(inputs, True))
  544. def vjp_fn(grad_output):
  545. return torch.autograd.grad(output, diff_input_list, grad_output,
  546. retain_graph=True, allow_unused=True)
  547. # Compute everything twice to check for nondeterminism (which we call reentrancy)
  548. vjps1 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  549. vjps2 = _compute_analytical_jacobian_rows(vjp_fn, output.clone())
  550. output_numel = output.numel()
  551. jacobians1, types_ok, sizes_ok = _stack_and_check_tensors(vjps1, inputs, output_numel)
  552. jacobians2, _, _ = _stack_and_check_tensors(vjps2, inputs, output_numel)
  553. reentrant = _check_jacobians_equal(jacobians1, jacobians2, nondet_tol)
  554. return jacobians1, reentrant, sizes_ok, types_ok
  555. def _get_analytical_jacobian(inputs, outputs, input_idx, output_idx):
  556. # Computes the analytical Jacobian in slow mode for a single input-output pair.
  557. # Forgoes performing checks on dtype, shape, and reentrancy.
  558. jacobians = _check_analytical_jacobian_attributes(inputs, outputs[output_idx],
  559. nondet_tol=float('inf'), check_grad_dtypes=False)
  560. return jacobians[input_idx]
  561. def _compute_analytical_jacobian_rows(vjp_fn, sample_output) -> List[List[Optional[torch.Tensor]]]:
  562. # Computes Jacobian row-by-row using backward function `vjp_fn` = v^T J
  563. # NB: this function does not assume vjp_fn(v) to return tensors with the same
  564. # number of elements for different v. This is checked when we later combine the
  565. # rows into a single tensor.
  566. grad_out_base = torch.zeros_like(sample_output, memory_format=torch.legacy_contiguous_format)
  567. flat_grad_out = grad_out_base.view(-1)
  568. # jacobians_rows[i][j] represents the jth row of the ith input
  569. jacobians_rows: List[List[Optional[torch.Tensor]]] = []
  570. for j in range(flat_grad_out.numel()):
  571. flat_grad_out.zero_()
  572. flat_grad_out[j] = 1.0
  573. grad_inputs = vjp_fn(grad_out_base)
  574. for i, d_x in enumerate(grad_inputs):
  575. if j == 0:
  576. jacobians_rows.append([])
  577. jacobians_rows[i] += [d_x.clone() if isinstance(d_x, torch.Tensor) else None]
  578. return jacobians_rows
  579. def _get_analytical_vjps_wrt_specific_output(vjp_fn, sample_output, v) -> List[List[Optional[torch.Tensor]]]:
  580. vjps: List[List[Optional[torch.Tensor]]] = []
  581. grad_inputs = vjp_fn(v.reshape(sample_output.shape))
  582. for vjp in grad_inputs:
  583. vjps.append([vjp.clone() if isinstance(vjp, torch.Tensor) else None])
  584. return vjps
  585. def _check_inputs(tupled_inputs, check_sparse_nnz) -> bool:
  586. if not check_sparse_nnz and any(_is_sparse_any_tensor(t) for t in tupled_inputs if isinstance(t, torch.Tensor)):
  587. raise GradcheckError('gradcheck expects all tensor inputs are dense when check_sparse_nnz is set to False.')
  588. # Make sure that gradients are saved for at least one input
  589. any_input_requiring_grad = False
  590. for idx, inp in enumerate(tupled_inputs):
  591. if is_tensor_like(inp) and inp.requires_grad:
  592. if not (inp.dtype == torch.float64 or inp.dtype == torch.complex128):
  593. warnings.warn(
  594. f'Input #{idx} requires gradient and '
  595. 'is not a double precision floating point or complex. '
  596. 'This check will likely fail if all the inputs are '
  597. 'not of double precision floating point or complex. ')
  598. if inp.is_sparse:
  599. content = inp._values()
  600. elif _is_sparse_compressed_tensor(inp):
  601. content = inp.values()
  602. else:
  603. content = inp
  604. # TODO: To cover more problematic cases, replace stride = 0 check with
  605. # "any overlap in memory" once we have a proper function to check it.
  606. if content.layout is not torch._mkldnn: # type: ignore[attr-defined]
  607. if not all(st > 0 or sz <= 1 for st, sz in zip(content.stride(), content.size())):
  608. raise RuntimeError(
  609. f'The {idx}th input has a dimension with stride 0. gradcheck only '
  610. 'supports inputs that are non-overlapping to be able to '
  611. 'compute the numerical gradients correctly. You should call '
  612. '.contiguous on the input before passing it to gradcheck.')
  613. any_input_requiring_grad = True
  614. inp.retain_grad()
  615. if not any_input_requiring_grad:
  616. raise ValueError(
  617. 'gradcheck expects at least one input tensor to require gradient, '
  618. 'but none of the them have requires_grad=True.')
  619. return True
  620. def _check_outputs(outputs) -> None:
  621. if any(_is_sparse_any_tensor(t) for t in outputs if isinstance(t, torch.Tensor)):
  622. # it is easier to call to_dense() on the sparse output than
  623. # to modify analytical jacobian
  624. raise ValueError('Sparse output is not supported at gradcheck yet. '
  625. 'Please call to_dense() on the output of fn for gradcheck.')
  626. if any(t.layout == torch._mkldnn for t in outputs if isinstance(t, torch.Tensor)): # type: ignore[attr-defined]
  627. raise ValueError('MKLDNN output is not supported at gradcheck yet. '
  628. 'Please call to_dense() on the output of fn for gradcheck.')
  629. def _check_no_differentiable_outputs(func, inputs, func_out, eps, *, is_forward_ad) -> bool:
  630. # When there are no differentiable outputs, numerical gradient for a function is
  631. # expected to be zero.
  632. jacobians_all_inputs_outputs = _get_numerical_jacobian(func, inputs, func_out,
  633. eps=eps, is_forward_ad=is_forward_ad)
  634. for jacobians_all_outputs_and_fixed_input in jacobians_all_inputs_outputs:
  635. for jacobian in jacobians_all_outputs_and_fixed_input:
  636. if torch.ne(jacobian, 0).sum() > 0:
  637. raise GradcheckError('Numerical gradient for function expected to be zero')
  638. return True
  639. def _check_no_differentiable_outputs_fast(func, func_out, all_inputs, inputs_indices,
  640. all_u, eps, nondet_tol):
  641. for inp_idx, u in zip(inputs_indices, all_u):
  642. jvps = _get_numerical_jvp_wrt_specific_input(func, inp_idx, all_inputs, u, eps)
  643. for jvp in jvps:
  644. if jvp.numel() == 0:
  645. continue
  646. if (jvp - torch.zeros_like(jvp)).abs().max() > nondet_tol:
  647. raise GradcheckError('Numerical gradient for function expected to be zero')
  648. return True
  649. FAILED_BATCHED_GRAD_MSG = """
  650. gradcheck or gradgradcheck failed while testing batched gradient computation.
  651. This could have been invoked in a number of ways (via a test that calls
  652. gradcheck/gradgradcheck directly or via an autogenerated test).
  653. If you are adding a new operator, please file an issue and then use one of the
  654. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  655. If the test
  656. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  657. with `check_batched_grad=False` as a keyword argument.
  658. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  659. to have `check_batched_grad=False` and/or `check_batched_gradgrad=False`.
  660. If you're modifying an existing operator that supports batched grad computation,
  661. or wish to make a new operator work with batched grad computation, please read
  662. the following.
  663. To compute batched grads (e.g., jacobians, hessians), we vmap over the backward
  664. computation. The most common failure case is if there is a 'vmap-incompatible
  665. operation' in the backward pass. Please see
  666. NOTE: [How to write vmap-compatible backward formulas]
  667. in the codebase for an explanation of how to fix this.
  668. """.strip()
  669. FAILED_BATCHED_GRAD_MSG_FWD_AD = """
  670. gradcheck failed while testing batched gradient computation with forward-mode AD.
  671. This test is enabled automatically when both `check_batched_grad=True`
  672. and `check_forward_ad=True`, but can be disabled in the following ways
  673. dependong on how the test was invoked (via a test that calls gradcheck
  674. directly or via an autogenerated test).
  675. If you are adding a new operator, please file an issue and then use one of the
  676. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck.
  677. If the test
  678. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  679. with `check_batched_forward_grad=False` as a keyword argument.
  680. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  681. to have `check_batched_forward_grad=False`
  682. """
  683. def _get_failed_batched_grad_test_msg(output_idx, input_idx, res, exp, is_forward_ad=False):
  684. return f"""
  685. For output {output_idx} and input {input_idx}:
  686. {FAILED_BATCHED_GRAD_MSG_FWD_AD if is_forward_ad else FAILED_BATCHED_GRAD_MSG}
  687. Got:
  688. {res}
  689. Expected:
  690. {exp}
  691. """.strip()
  692. def _test_batched_grad_forward_ad(func, inputs) -> bool:
  693. fwAD = torch.autograd.forward_ad # To avoid early import issues (do we need this?)
  694. assert isinstance(inputs, tuple)
  695. for input_idx, current_input in enumerate(inputs):
  696. if not (is_tensor_like(current_input) and current_input.requires_grad):
  697. continue
  698. def jvp(tangent: torch.Tensor):
  699. with fwAD.dual_level():
  700. dual = fwAD.make_dual(current_input.detach(), tangent)
  701. inputs_with_dual = tuple(dual if idx == input_idx else (inp.detach() if is_tensor_like(inp) else inp)
  702. for idx, inp in enumerate(inputs))
  703. dual_outputs = _as_tuple(func(*inputs_with_dual))
  704. ret = []
  705. for dual_output in dual_outputs:
  706. if dual_output is None:
  707. continue
  708. primal_out, tangent_out = fwAD.unpack_dual(dual_output)
  709. if tangent_out is not None:
  710. ret.append(tangent_out)
  711. else:
  712. ret.append(torch.zeros([], dtype=primal_out.dtype, device=primal_out.device).expand(primal_out.shape))
  713. return tuple(ret)
  714. if not _is_float_or_complex_tensor(current_input):
  715. continue
  716. tangents = [torch.randn_like(current_input) for _ in range(2)]
  717. expected = [jvp(t) for t in tangents]
  718. expected = [torch.stack(shards) for shards in zip(*expected)]
  719. try:
  720. result = _vmap(jvp)(torch.stack(tangents))
  721. except RuntimeError as ex:
  722. # Rethrow to provide a better error message
  723. raise GradcheckError(
  724. f'While computing batched gradients, got: {ex}\n\n{FAILED_BATCHED_GRAD_MSG_FWD_AD}') from ex
  725. for input_idx, (res, exp) in enumerate(zip(result, expected)):
  726. if torch.allclose(res, exp):
  727. continue
  728. raise GradcheckError(_get_failed_batched_grad_test_msg(input_idx, input_idx, res, exp, is_forward_ad=True))
  729. return True
  730. def _test_batched_grad(input, output, output_idx) -> bool:
  731. # NB: _test_batched_grad compares two autograd.grad invocations with a single
  732. # vmap(autograd.grad) invocation. It's not exactly a "gradcheck" in the
  733. # sense that we're not comparing an analytical jacobian with a numeric one,
  734. # but it is morally similar (we could have computed a full analytic jac
  735. # via vmap, but that is potentially slow)
  736. diff_input_list = list(_iter_tensors(input, True))
  737. grad = functools.partial(torch.autograd.grad, output, diff_input_list, retain_graph=True, allow_unused=True)
  738. def vjp(v):
  739. results = grad(v)
  740. results = tuple(grad if grad is not None else
  741. torch.zeros([], dtype=inp.dtype, device=inp.device).expand(inp.shape)
  742. for grad, inp in zip(results, diff_input_list))
  743. return results
  744. grad_outputs = [torch.randn_like(output) for _ in range(2)]
  745. expected = [vjp(gO) for gO in grad_outputs]
  746. expected = [torch.stack(shards) for shards in zip(*expected)]
  747. # Squash warnings since these are expected to happen in most cases
  748. # NB: this doesn't work for CUDA tests: https://github.com/pytorch/pytorch/issues/50209
  749. with warnings.catch_warnings():
  750. warnings.filterwarnings("ignore", message="There is a performance drop")
  751. warnings.filterwarnings("ignore", message="Please use torch.vmap")
  752. try:
  753. result = vmap(vjp)(torch.stack(grad_outputs))
  754. except RuntimeError as ex:
  755. # It's OK that we're not raising the error at the correct callsite.
  756. # That's because the callsite is always going to inside the Python
  757. # autograd.grad instead of the C++ traceback of what line in the
  758. # backward formula
  759. raise GradcheckError(
  760. f'While computing batched gradients, got: {ex}\n\n{FAILED_BATCHED_GRAD_MSG}') from ex
  761. for input_idx, (res, exp) in enumerate(zip(result, expected)):
  762. if torch.allclose(res, exp):
  763. continue
  764. raise GradcheckError(_get_failed_batched_grad_test_msg(output_idx, input_idx, res, exp))
  765. return True
  766. def _test_backward_mul_by_grad_output(outputs, inputs, check_sparse_nnz) -> bool:
  767. # Tests that backward is multiplied by grad_output
  768. diff_input_list: List[torch.Tensor] = list(_iter_tensors(inputs, True))
  769. if not diff_input_list:
  770. raise GradcheckError("no Tensors requiring grad found in input")
  771. grads_input = torch.autograd.grad(outputs, diff_input_list,
  772. [torch.zeros_like(o, memory_format=torch.legacy_contiguous_format) for o in outputs],
  773. allow_unused=True)
  774. for gi, di in zip(grads_input, diff_input_list):
  775. if gi is None:
  776. continue
  777. if isinstance(gi, torch.Tensor) and gi.layout != torch.strided:
  778. if gi.layout != di.layout:
  779. raise GradcheckError('grad is incorrect layout (' + str(gi.layout) + ' is not ' + str(di.layout) + ')')
  780. if _is_sparse_any_tensor(gi):
  781. sparse_kind = str(gi.layout).replace('torch.', '').replace('_coo', '')
  782. if gi.sparse_dim() != di.sparse_dim():
  783. raise GradcheckError(f'grad is {sparse_kind} tensor, but has incorrect sparse_dim')
  784. if gi.dense_dim() != di.dense_dim():
  785. raise GradcheckError(f'grad is {sparse_kind} tensor, but has incorrect dense_dim')
  786. gi = gi.to_dense()
  787. di = di.to_dense()
  788. if check_sparse_nnz:
  789. if not torch.allclose(gi, torch.zeros_like(gi)):
  790. raise GradcheckError('backward not multiplied by grad_output')
  791. elif not gi.eq(0).all():
  792. raise GradcheckError('backward not multiplied by grad_output')
  793. if gi.dtype != di.dtype or gi.device != di.device or gi.is_sparse != di.is_sparse:
  794. raise GradcheckError("grad is incorrect type")
  795. if gi.size() != di.size():
  796. raise GradcheckError('grad is incorrect size')
  797. return True
  798. def _test_undefined_forward_mode(func, outputs, inputs):
  799. fwAD = torch.autograd.forward_ad
  800. inp_tensors_idx, inp_tensors = _get_inp_tensors(inputs)
  801. all_v, all_u, all_u_dense = _make_vectors(inp_tensors, outputs, use_forward_ad=True)
  802. tensor_inputs = tuple(i for i in inputs if is_tensor_like(i) and i.requires_grad)
  803. with fwAD.dual_level():
  804. fw_grads = []
  805. dual_inputs = []
  806. tensor_indices = set()
  807. for i, inp in enumerate(inputs):
  808. if is_tensor_like(inp) and inp.requires_grad:
  809. if inp.layout == torch._mkldnn: # type: ignore[attr-defined]
  810. raise ValueError("MKLDNN inputs are not support for forward AD gradcheck.")
  811. inp = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  812. # If inp is a differentiable view, the dual might not be the tangent given to
  813. # make_dual, so read it explicitly from the dual tensor
  814. fw_grads.append(fwAD.unpack_dual(inp)[1])
  815. tensor_indices.add(i)
  816. dual_inputs.append(inp)
  817. for i, (fw_grad, u) in enumerate(zip(fw_grads, all_u)):
  818. fw_grad.copy_(u.view_as(fw_grad))
  819. for idx, inp in enumerate(inputs):
  820. if idx not in tensor_indices:
  821. continue
  822. dual_inp_obj = dual_inputs[idx]
  823. # case 1 (Materialized Zero Tensor Tangent)
  824. dual_inputs[idx] = fwAD.make_dual(inp.detach(), torch.zeros_like(inp))
  825. raw_outputs = _as_tuple(func(*dual_inputs))
  826. dual_outputs1 = filter(_is_float_or_complex_tensor, raw_outputs)
  827. # case 2 (Efficient Zero Tensor Tangent since we don't make a dual object and pass a regular tensor)
  828. dual_inputs[idx] = inp.detach()
  829. raw_outputs = _as_tuple(func(*dual_inputs))
  830. dual_outputs2 = filter(_is_float_or_complex_tensor, raw_outputs)
  831. # reset
  832. dual_inputs[idx] = dual_inp_obj
  833. for index_o, (d_o1, d_o2) in enumerate(zip(dual_outputs1, dual_outputs2)):
  834. val1, res1 = fwAD.unpack_dual(d_o1)
  835. val2, res2 = fwAD.unpack_dual(d_o2)
  836. if not (res1 is None or res2 is None):
  837. if not torch.allclose(res1, res2):
  838. raise GradcheckError("Mismatch in tangent values for output with index: ", index_o,
  839. " when input: ", inp, " has an undefined tangent value. ",
  840. " Got: ", res1, " but expected: ", res2)
  841. return True
  842. def _test_undefined_backward_mode(func, outputs, inputs) -> bool:
  843. diff_input_list: List[torch.Tensor] = list(_iter_tensors(inputs, True))
  844. if not diff_input_list:
  845. raise GradcheckError("no Tensors requiring grad found in input")
  846. def warn_bc_breaking():
  847. warnings.warn((
  848. 'Backwards compatibility: New undefined gradient support checking '
  849. 'feature is enabled by default, but it may break existing callers '
  850. 'of this function. If this is true for you, you can call this '
  851. 'function with "check_undefined_grad=False" to disable the feature'))
  852. def check_undefined_grad_support(output_to_check):
  853. grads_output = [torch.zeros_like(o, memory_format=torch.legacy_contiguous_format) for o in output_to_check]
  854. try:
  855. grads_input = torch.autograd.grad(output_to_check, diff_input_list,
  856. grads_output, allow_unused=True)
  857. except RuntimeError as e:
  858. warn_bc_breaking()
  859. raise GradcheckError((
  860. 'Expected backward function to handle undefined output grads. '
  861. 'Please look at "Notes about undefined output gradients" in '
  862. '"tools/autograd/derivatives.yaml"')) from e
  863. for gi, i in zip(grads_input, diff_input_list):
  864. if (gi is not None) and (not gi.eq(0).all()):
  865. warn_bc_breaking()
  866. raise GradcheckError((
  867. 'Expected all input grads to be undefined or zero when all output grads are undefined '
  868. 'or zero. Please look at "Notes about undefined output gradients" in '
  869. '"tools/autograd/derivatives.yaml"'))
  870. return True
  871. # All backward functions must work properly if all output grads are undefined
  872. outputs_to_check = [[
  873. torch._C._functions.UndefinedGrad()(o) for o in _differentiable_outputs(func(*inputs))
  874. # This check filters out Tensor-likes that aren't instances of Tensor.
  875. if isinstance(o, torch.Tensor)
  876. ]]
  877. # If there are multiple output grads, we should be able to undef one at a time without error
  878. if len(outputs_to_check[0]) > 1:
  879. for undef_grad_idx in range(len(outputs)):
  880. output_to_check = _differentiable_outputs(func(*inputs))
  881. outputs_to_check.append([
  882. torch._C._functions.UndefinedGrad()(o) if idx == undef_grad_idx else o
  883. for idx, o in enumerate(output_to_check)])
  884. return all(check_undefined_grad_support(output) for output in outputs_to_check)
  885. def _as_tuple(x):
  886. if isinstance(x, tuple):
  887. return x
  888. elif isinstance(x, list):
  889. return tuple(x)
  890. else:
  891. return x,
  892. def _differentiable_outputs(x):
  893. return tuple(o for o in _as_tuple(x) if o.requires_grad)
  894. def _get_notallclose_msg(analytical, numerical, output_idx, input_idx, complex_indices,
  895. test_imag=False, is_forward_ad=False) -> str:
  896. out_is_complex = (not is_forward_ad) and complex_indices and output_idx in complex_indices
  897. inp_is_complex = is_forward_ad and complex_indices and input_idx in complex_indices
  898. part = "imaginary" if test_imag else "real"
  899. element = "inputs" if is_forward_ad else "outputs"
  900. prefix = "" if not (out_is_complex or inp_is_complex) else \
  901. f"While considering the {part} part of complex {element} only, "
  902. mode = "computed with forward mode " if is_forward_ad else ""
  903. return prefix + 'Jacobian %smismatch for output %d with respect to input %d,\n' \
  904. 'numerical:%s\nanalytical:%s\n' % (mode, output_idx, input_idx, numerical, analytical)
  905. def _transpose(matrix_of_tensors):
  906. # returns list of tuples
  907. return list(zip(*matrix_of_tensors))
  908. def _real_and_imag_output(fn):
  909. # returns new functions real(fn), and imag(fn) where real(fn) and imag(fn) behave the same as
  910. # the original fn, except torch.real or torch.imag are applied to the complex outputs
  911. def apply_to_c_outs(fn, fn_to_apply):
  912. def wrapped_fn(*inputs):
  913. outs = _as_tuple(fn(*inputs))
  914. return tuple(fn_to_apply(o) if o.is_complex() else o for o in outs)
  915. return wrapped_fn
  916. return apply_to_c_outs(fn, torch.real), apply_to_c_outs(fn, torch.imag)
  917. def _real_and_imag_input(fn, complex_inp_indices, tupled_inputs):
  918. # returns new functions that take real inputs instead of complex inputs as
  919. # (x, y) -> fn(x + y * 1j). And it computes: inp -> fn(inp + y * 1j) and inp -> fn(x + inp * 1j).
  920. # In each case, the other part is considered constant.
  921. # We do not use 0 for the constant here to make sure we always call the user function with a valid input.
  922. def apply_to_c_inps(fn, fn_to_apply):
  923. def wrapped_fn(*inputs):
  924. new_inputs = list(inputs)
  925. for should_be_complex in complex_inp_indices:
  926. new_inputs[should_be_complex] = fn_to_apply(new_inputs[should_be_complex],
  927. tupled_inputs[should_be_complex])
  928. return _as_tuple(fn(*new_inputs))
  929. return wrapped_fn
  930. real_fn = apply_to_c_inps(fn, lambda inp, orig: inp + orig.imag * 1j)
  931. imag_fn = apply_to_c_inps(fn, lambda inp, orig: orig.real + inp * 1j)
  932. return real_fn, imag_fn
  933. def _gradcheck_real_imag(gradcheck_fn, func, func_out, tupled_inputs, outputs, eps, rtol,
  934. atol, check_grad_dtypes, check_forward_ad, check_backward_ad, nondet_tol,
  935. check_undefined_grad):
  936. complex_out_indices = [i for i, o in enumerate(outputs) if o.is_complex()]
  937. has_any_complex_output = any(o.is_complex() for o in _as_tuple(func_out))
  938. if check_backward_ad:
  939. if has_any_complex_output:
  940. real_fn, imag_fn = _real_and_imag_output(func)
  941. imag_func_out = imag_fn(*tupled_inputs)
  942. imag_outputs = _differentiable_outputs(imag_func_out)
  943. gradcheck_fn(imag_fn, imag_func_out, tupled_inputs, imag_outputs, eps,
  944. rtol, atol, check_grad_dtypes, nondet_tol,
  945. complex_indices=complex_out_indices, test_imag=True)
  946. real_func_out = real_fn(*tupled_inputs)
  947. real_outputs = _differentiable_outputs(real_func_out)
  948. gradcheck_fn(real_fn, real_func_out, tupled_inputs, real_outputs, eps,
  949. rtol, atol, check_grad_dtypes, nondet_tol, complex_indices=complex_out_indices)
  950. else:
  951. gradcheck_fn(func, func_out, tupled_inputs, outputs, eps,
  952. rtol, atol, check_grad_dtypes, nondet_tol)
  953. if check_forward_ad:
  954. complex_inp_indices = [i for i, inp in enumerate(tupled_inputs) if is_tensor_like(inp) and inp.is_complex()]
  955. if complex_inp_indices:
  956. real_fn, imag_fn = _real_and_imag_input(func, complex_inp_indices, tupled_inputs)
  957. imag_inputs = [inp.imag if is_tensor_like(inp) and inp.is_complex() else inp for inp in tupled_inputs]
  958. imag_func_out = imag_fn(*imag_inputs)
  959. diff_imag_func_out = _differentiable_outputs(imag_func_out)
  960. gradcheck_fn(imag_fn, imag_func_out, imag_inputs, diff_imag_func_out, eps,
  961. rtol, atol, check_grad_dtypes, nondet_tol,
  962. complex_indices=complex_inp_indices, test_imag=True, use_forward_ad=True)
  963. real_inputs = [inp.real if is_tensor_like(inp) and inp.is_complex() else inp for inp in tupled_inputs]
  964. real_func_out = real_fn(*real_inputs)
  965. diff_real_func_out = _differentiable_outputs(real_func_out)
  966. gradcheck_fn(real_fn, real_func_out, real_inputs, diff_real_func_out, eps,
  967. rtol, atol, check_grad_dtypes, nondet_tol, complex_indices=complex_inp_indices,
  968. use_forward_ad=True)
  969. if check_undefined_grad:
  970. _test_undefined_forward_mode(imag_fn, imag_func_out, imag_inputs)
  971. _test_undefined_forward_mode(real_fn, real_func_out, real_inputs)
  972. else:
  973. gradcheck_fn(func, func_out, tupled_inputs, outputs, eps,
  974. rtol, atol, check_grad_dtypes, nondet_tol, use_forward_ad=True)
  975. if check_undefined_grad:
  976. _test_undefined_forward_mode(func, outputs, tupled_inputs)
  977. def _slow_gradcheck(func, func_out, tupled_inputs, outputs, eps, rtol, atol, check_grad_dtypes,
  978. nondet_tol, *, use_forward_ad=False, complex_indices=None, test_imag=False):
  979. func_out = _as_tuple(func_out)
  980. if not outputs:
  981. return _check_no_differentiable_outputs(func, tupled_inputs, func_out,
  982. eps=eps, is_forward_ad=use_forward_ad)
  983. numerical = _transpose(_get_numerical_jacobian(func, tupled_inputs, func_out, eps=eps, is_forward_ad=use_forward_ad))
  984. # Note: [numerical vs analytical output length]
  985. # The numerical path returns jacobian quantity for all outputs, even if requires_grad of that
  986. # output is False. This behavior is necessary for _check_no_differentiable_outputs to work.
  987. numerical = [nj for o, nj in zip(func_out, numerical) if o.requires_grad]
  988. if use_forward_ad:
  989. analytical_forward = _get_analytical_jacobian_forward_ad(func, tupled_inputs, func_out, check_grad_dtypes=check_grad_dtypes)
  990. for i, n_per_out in enumerate(numerical):
  991. for j, n in enumerate(n_per_out):
  992. a = analytical_forward[j][i]
  993. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, atol):
  994. raise GradcheckError(_get_notallclose_msg(a, n, i, j, complex_indices, test_imag,
  995. is_forward_ad=True))
  996. else:
  997. for i, o in enumerate(outputs):
  998. analytical = _check_analytical_jacobian_attributes(tupled_inputs, o, nondet_tol, check_grad_dtypes)
  999. for j, (a, n) in enumerate(zip(analytical, numerical[i])):
  1000. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, atol):
  1001. raise GradcheckError(_get_notallclose_msg(a, n, i, j, complex_indices, test_imag))
  1002. return True
  1003. def _dot_with_type_promotion(u, v):
  1004. assert u.dim() == 1 and v.dim() == 1
  1005. return (u * v).sum()
  1006. def _allclose_with_type_promotion(a, b, rtol, atol):
  1007. promoted_type = torch.promote_types(a.dtype, b.dtype)
  1008. a = a.to(dtype=promoted_type)
  1009. b = b.to(dtype=promoted_type)
  1010. return torch.allclose(a, b, rtol, atol)
  1011. def _to_real_dtype(dtype):
  1012. if dtype == torch.complex128:
  1013. return torch.float64
  1014. elif dtype == torch.complex64:
  1015. return torch.float32
  1016. else:
  1017. return dtype
  1018. def _vec_from_tensor(x, generator, downcast_complex=False):
  1019. # Create a random vector with the same number of elements as x and the same
  1020. # dtype/device. If x is complex and downcast_complex is False, we create a
  1021. # complex tensor with only real component.
  1022. if x.layout == torch.sparse_coo:
  1023. # For sparse, create a random sparse vec with random values in the same
  1024. # indices. Make sure size is set so that it isn't inferred to be smaller.
  1025. x_values = x._values()
  1026. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1027. values = torch.rand(x_values.numel(), generator=generator) \
  1028. .to(dtype=dtype, device=x.device) \
  1029. .view(x_values.shape)
  1030. values /= values.norm()
  1031. vec = torch.sparse_coo_tensor(x._indices(), values, x.size())
  1032. elif _is_sparse_compressed_tensor(x):
  1033. if x.layout in {torch.sparse_csr, torch.sparse_bsr}:
  1034. compressed_indices, plain_indices = x.crow_indices(), x.col_indices()
  1035. else:
  1036. compressed_indices, plain_indices = x.ccol_indices(), x.row_indices()
  1037. x_values = x.values()
  1038. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1039. values = torch.rand(x_values.numel(), generator=generator) \
  1040. .to(dtype=dtype, device=x.device) \
  1041. .view(x_values.shape)
  1042. values /= values.norm()
  1043. vec = torch.sparse_compressed_tensor(compressed_indices, plain_indices, values, x.size(), layout=x.layout)
  1044. else:
  1045. dtype = _to_real_dtype(x.dtype) if downcast_complex else x.dtype
  1046. vec = torch.rand(x.numel(), generator=generator).to(dtype=dtype, device=x.device)
  1047. vec /= vec.norm()
  1048. return vec
  1049. def _get_inp_tensors(tupled_inputs):
  1050. inp_idx_tup = [(i, t) for i, t in enumerate(tupled_inputs) if is_tensor_like(t) and t.requires_grad]
  1051. return [tup[0] for tup in inp_idx_tup], [tup[1] for tup in inp_idx_tup]
  1052. def _adjusted_atol(atol, u, v):
  1053. # In slow gradcheck, we compare A and B element-wise, i.e., for some a, b we
  1054. # allow: |a - b| < atol + rtol * b. But since we now compare q1 = v^T A u and
  1055. # q2 = v^T B u, we must allow |q1 - q2| < v^T E u + rtol * v^T B u, where E is
  1056. # the correctly sized matrix in which each entry is atol.
  1057. #
  1058. # We see that atol needs to be scaled by v^T M u (where M is an all-ones M x N
  1059. # matrix): v^T M u = \sum_{i} \sum_{j} u_i * v_j = (\sum_{i} u_i)(\sum_{i} v_i)
  1060. # TODO: properly handle case when u is tuple instead of only taking first element
  1061. u = u[0] if isinstance(u, tuple) else u
  1062. # TODO: replace torch.sparse.sum(u) with u.sum()
  1063. sum_u = torch.sparse.sum(u) if u.layout == torch.sparse_coo else u.sum()
  1064. sum_v = 1. if v is None else torch.sparse.sum(v) if v.layout == torch.sparse_coo else v.sum()
  1065. return atol * float(sum_u) * float(sum_v)
  1066. FAST_FAIL_SLOW_OK_MSG = """
  1067. Fast gradcheck failed but element-wise differences are small. This means that the
  1068. test might've passed in slow_mode!
  1069. If you are adding a new operator, please file an issue and then use one of the
  1070. workarounds. The workaround depends on how your test invokes gradcheck/gradgradcheck:
  1071. If the test
  1072. - manually invokes gradcheck/gradgradcheck, then call gradcheck/gradgradcheck
  1073. with `fast_mode=False` as a keyword argument.
  1074. - is OpInfo-based (e.g., in test_ops_gradients.py), then modify the OpInfo for the test
  1075. to have `gradcheck_fast_mode=False`
  1076. - is a Module test (e.g., in common_nn.py), then modify the corresponding
  1077. module_test entry to have `gradcheck_fast_mode=False`
  1078. """.strip()
  1079. def _run_slow_mode_and_get_error(func, tupled_inputs, outputs, input_idx, output_idx, rtol, atol, is_forward_ad):
  1080. # Compute jacobians in slow mode for better error message
  1081. slow_numerical = _get_numerical_jacobian(func, tupled_inputs, outputs, is_forward_ad=is_forward_ad)[input_idx][output_idx]
  1082. if is_forward_ad:
  1083. def new_fn(inp):
  1084. new_inputs = list(tupled_inputs)
  1085. new_inputs[input_idx] = inp
  1086. return _as_tuple(func(*new_inputs))[output_idx]
  1087. slow_analytical = _get_analytical_jacobian_forward_ad(new_fn, (tupled_inputs[input_idx],), (outputs[output_idx],))[0][0]
  1088. else:
  1089. slow_analytical = _get_analytical_jacobian(tupled_inputs, outputs, input_idx, output_idx)
  1090. # Assume jacobians are non-empty and have the same shape
  1091. slow_max_diff = (slow_numerical - slow_analytical).abs().max()
  1092. slow_allclose = torch.allclose(slow_analytical, slow_numerical, rtol, atol)
  1093. msg = ("\nThe above quantities relating the numerical and analytical jacobians are computed \n"
  1094. "in fast mode. See: https://github.com/pytorch/pytorch/issues/53876 for more background \n"
  1095. "about fast mode. Below, we recompute numerical and analytical jacobians in slow mode:\n\n"
  1096. f"Numerical:\n {slow_numerical}\n"
  1097. f"Analytical:\n{slow_analytical}\n\n"
  1098. f"The max per-element difference (slow mode) is: {slow_max_diff}.\n")
  1099. if slow_allclose:
  1100. # Slow gradcheck would've passed!
  1101. msg += FAST_FAIL_SLOW_OK_MSG
  1102. return msg
  1103. def _to_flat_dense_if_sparse(tensor):
  1104. if _is_sparse_any_tensor(tensor):
  1105. return tensor.to_dense().reshape(-1)
  1106. else:
  1107. return tensor
  1108. def _make_vectors(inp_tensors, outputs, *, use_forward_ad):
  1109. # Use our own generator to avoid messing with the user's RNG state
  1110. g_cpu = torch.Generator()
  1111. all_u = []
  1112. all_u_dense = []
  1113. for inp in inp_tensors:
  1114. ur = _vec_from_tensor(inp, g_cpu, True)
  1115. ur_dense = _to_flat_dense_if_sparse(ur)
  1116. if inp.is_complex():
  1117. ui = _vec_from_tensor(inp, g_cpu, True)
  1118. all_u.append((ur, ui))
  1119. ui_dense = _to_flat_dense_if_sparse(ui)
  1120. all_u_dense.append((ur_dense, ui_dense))
  1121. else:
  1122. all_u.append(ur)
  1123. all_u_dense.append(ur_dense)
  1124. all_v = None if use_forward_ad else [_vec_from_tensor(out, g_cpu) for out in outputs]
  1125. return all_v, all_u, all_u_dense
  1126. def _check_analytical_numerical_equal(all_analytical, all_numerical, complex_indices, tupled_inputs, outputs,
  1127. func, all_v, all_u, rtol, atol, test_imag, *, is_forward_ad=False):
  1128. for i, all_numerical_for_input_i in enumerate(all_numerical):
  1129. for j, n in enumerate(all_numerical_for_input_i):
  1130. # Forward AD generates the transpose of what this function expects
  1131. if is_forward_ad:
  1132. a = all_analytical[i][j]
  1133. else:
  1134. a = all_analytical[j][i]
  1135. n = n.to(device=a.device)
  1136. updated_atol = _adjusted_atol(atol, all_u[i], all_v[j] if all_v else None)
  1137. if not _allclose_with_type_promotion(a, n.to(a.device), rtol, updated_atol):
  1138. jacobians_str = _run_slow_mode_and_get_error(func, tupled_inputs, outputs, i, j, rtol, atol, is_forward_ad)
  1139. raise GradcheckError(_get_notallclose_msg(a, n, j, i, complex_indices, test_imag, is_forward_ad) + jacobians_str)
  1140. def _fast_gradcheck(func, func_out, inputs, outputs, eps, rtol,
  1141. atol, check_grad_dtypes, nondet_tol, *, use_forward_ad=False, complex_indices=None, test_imag=False):
  1142. # See https://github.com/pytorch/pytorch/issues/53876 for details
  1143. inp_tensors_idx, inp_tensors = _get_inp_tensors(inputs)
  1144. # Backward mode computes v^T * J (VJP)
  1145. # Since we computed J * u (JVP) through finite difference method, we perform an equality check
  1146. # between VJP * u, v * JVP
  1147. # ----
  1148. # Forward mode computes J * u (JVP)
  1149. # Since we already compute JVP through finite difference method,
  1150. # we don't need v for correctness check here as asserted below
  1151. all_v, all_u, all_u_dense = _make_vectors(inp_tensors, outputs, use_forward_ad=use_forward_ad)
  1152. numerical_vJu = _get_numerical_vJu(func, inputs, inp_tensors_idx, func_out, all_u, all_v, eps, is_forward_ad=use_forward_ad)
  1153. # TODO: replicate https://github.com/pytorch/pytorch/pull/77743 for fast gradcheck as well
  1154. if use_forward_ad:
  1155. assert all_v is None
  1156. analytical_vJu = _get_analytical_jacobian_forward_ad(func, inputs, _as_tuple(func_out),
  1157. all_u=all_u, check_grad_dtypes=check_grad_dtypes)
  1158. else:
  1159. if not outputs:
  1160. _check_no_differentiable_outputs_fast(func, func_out, inputs, inp_tensors_idx, all_u, eps, nondet_tol)
  1161. analytical_vJu = _get_analytical_vJu_backward_mode(inputs, outputs, nondet_tol, check_grad_dtypes, all_v, all_u_dense)
  1162. _check_analytical_numerical_equal(analytical_vJu, numerical_vJu, complex_indices,
  1163. inputs, outputs, func, all_v, all_u, rtol, atol, test_imag, is_forward_ad=use_forward_ad)
  1164. return True
  1165. # Note [VarArg of Tensors]
  1166. # ~~~~~~~~~~~~~~~~~~~~~~~~
  1167. # 'func' accepts a vararg of tensors, which isn't expressable in the type system at the moment.
  1168. # If https://mypy.readthedocs.io/en/latest/additional_features.html?highlight=callable#extended-callable-types is accepted,
  1169. # the '...' first argument of Callable can be replaced with VarArg(Tensor).
  1170. # For now, we permit any input.
  1171. # the '...' first argument of Callable can be replaced with VarArg(Tensor).
  1172. # For now, we permit any input.
  1173. def gradcheck(
  1174. func: Callable[..., Union[_TensorOrTensors]], # See Note [VarArg of Tensors]
  1175. inputs: _TensorOrTensors,
  1176. *,
  1177. eps: float = 1e-6,
  1178. atol: float = 1e-5,
  1179. rtol: float = 1e-3,
  1180. raise_exception: bool = True,
  1181. check_sparse_nnz: bool = False,
  1182. nondet_tol: float = 0.0,
  1183. check_undefined_grad: bool = True,
  1184. check_grad_dtypes: bool = False,
  1185. check_batched_grad: bool = False,
  1186. check_batched_forward_grad: bool = False,
  1187. check_forward_ad: bool = False,
  1188. check_backward_ad: bool = True,
  1189. fast_mode: bool = False,
  1190. ) -> bool:
  1191. r"""Check gradients computed via small finite differences against analytical
  1192. gradients w.r.t. tensors in :attr:`inputs` that are of floating point or complex type
  1193. and with ``requires_grad=True``.
  1194. The check between numerical and analytical gradients uses :func:`~torch.allclose`.
  1195. For most of the complex functions we consider for optimization purposes, no notion of
  1196. Jacobian exists. Instead, gradcheck verifies if the numerical and analytical values of
  1197. the Wirtinger and Conjugate Wirtinger derivatives are consistent. Because the gradient
  1198. computation is done under the assumption that the overall function has a real-valued
  1199. output, we treat functions with complex output in a special way. For these functions,
  1200. gradcheck is applied to two real-valued functions corresponding to taking the real
  1201. components of the complex outputs for the first, and taking the imaginary components
  1202. of the complex outputs for the second. For more details, check out
  1203. :ref:`complex_autograd-doc`.
  1204. .. note::
  1205. The default values are designed for :attr:`input` of double precision.
  1206. This check will likely fail if :attr:`input` is of less precision, e.g.,
  1207. ``FloatTensor``.
  1208. .. note::
  1209. Gradcheck may fail when evaluated on non-differentiable points
  1210. because the numerically computed gradients via finite differencing may differ
  1211. those computed analytically (not necessarily because either is incorrect).
  1212. For more context, see :ref:`non-differentiable-func-grad`.
  1213. .. warning::
  1214. If any checked tensor in :attr:`input` has overlapping memory, i.e.,
  1215. different indices pointing to the same memory address (e.g., from
  1216. :func:`torch.expand`), this check will likely fail because the numerical
  1217. gradients computed by point perturbation at such indices will change
  1218. values at all other indices that share the same memory address.
  1219. Args:
  1220. func (function): a Python function that takes Tensor inputs and returns
  1221. a Tensor or a tuple of Tensors
  1222. inputs (tuple of Tensor or Tensor): inputs to the function
  1223. eps (float, optional): perturbation for finite differences
  1224. atol (float, optional): absolute tolerance
  1225. rtol (float, optional): relative tolerance
  1226. raise_exception (bool, optional): indicating whether to raise an exception if
  1227. the check fails. The exception gives more information about the
  1228. exact nature of the failure. This is helpful when debugging gradchecks.
  1229. check_sparse_nnz (bool, optional): if True, gradcheck allows for SparseTensor input,
  1230. and for any SparseTensor at input, gradcheck will perform check at nnz positions only.
  1231. nondet_tol (float, optional): tolerance for non-determinism. When running
  1232. identical inputs through the differentiation, the results must either match
  1233. exactly (default, 0.0) or be within this tolerance.
  1234. check_undefined_grad (bool, optional): if True, check if undefined output grads
  1235. are supported and treated as zeros, for ``Tensor`` outputs.
  1236. check_batched_grad (bool, optional): if True, check if we can compute
  1237. batched gradients using prototype vmap support. Defaults to False.
  1238. check_batched_forward_grad (bool, optional): if True, checks if we can compute
  1239. batched forward gradients using forward ad and prototype vmap support. Defaults to False.
  1240. check_forward_ad (bool, optional): if True, check that the gradients computed with forward
  1241. mode AD match the numerical ones. Defaults to False.
  1242. check_backward_ad (bool, optional): if False, do not perform any checks that rely on
  1243. backward mode AD to be implemented. Defaults to True.
  1244. fast_mode (bool, optional): Fast mode for gradcheck and gradgradcheck is currently only
  1245. implemented for R to R functions. If none of the inputs and outputs are complex
  1246. a faster implementation of gradcheck that no longer computes the entire jacobian
  1247. is run; otherwise, we fall back to the slow implementation.
  1248. Returns:
  1249. True if all differences satisfy allclose condition
  1250. """
  1251. assert check_forward_ad or check_backward_ad, \
  1252. "Expected at least one of check_forward_ad or check_backward_ad to be True"
  1253. assert not (check_batched_grad and not check_backward_ad), (
  1254. "Setting check_batched_grad=True requires check_backward_ad to be True")
  1255. assert not (check_batched_forward_grad and not check_forward_ad), (
  1256. "Setting check_batched_forward_grad=True requires check_forward_ad to be True")
  1257. args = locals().copy()
  1258. args.pop("raise_exception")
  1259. if not raise_exception:
  1260. try:
  1261. return _gradcheck_helper(**args)
  1262. except GradcheckError as e:
  1263. return False
  1264. else:
  1265. return _gradcheck_helper(**args)
  1266. def _gradcheck_helper(func, inputs, eps, atol, rtol, check_sparse_nnz, nondet_tol, check_undefined_grad,
  1267. check_grad_dtypes, check_batched_grad, check_batched_forward_grad, check_forward_ad,
  1268. check_backward_ad, fast_mode):
  1269. tupled_inputs = _as_tuple(inputs)
  1270. _check_inputs(tupled_inputs, check_sparse_nnz)
  1271. func_out = func(*tupled_inputs)
  1272. outputs = _differentiable_outputs(func_out)
  1273. _check_outputs(outputs)
  1274. gradcheck_fn = _fast_gradcheck if fast_mode else _slow_gradcheck
  1275. _gradcheck_real_imag(gradcheck_fn, func, func_out, tupled_inputs, outputs, eps,
  1276. rtol, atol, check_grad_dtypes, check_forward_ad=check_forward_ad,
  1277. check_backward_ad=check_backward_ad, nondet_tol=nondet_tol,
  1278. check_undefined_grad=check_undefined_grad)
  1279. if check_batched_forward_grad:
  1280. _test_batched_grad_forward_ad(func, tupled_inputs)
  1281. # Short circuit because remaining tests rely on backward AD to be implemented
  1282. if not check_backward_ad:
  1283. return True
  1284. for i, o in enumerate(outputs):
  1285. if check_batched_grad:
  1286. _test_batched_grad(tupled_inputs, o, i)
  1287. _test_backward_mul_by_grad_output(outputs, tupled_inputs, check_sparse_nnz)
  1288. if check_undefined_grad and check_backward_ad:
  1289. _test_undefined_backward_mode(func, outputs, tupled_inputs)
  1290. return True
  1291. def gradgradcheck(
  1292. func: Callable[..., _TensorOrTensors], # See Note [VarArg of Tensors]
  1293. inputs: _TensorOrTensors,
  1294. grad_outputs: Optional[_TensorOrTensors] = None,
  1295. *,
  1296. eps: float = 1e-6,
  1297. atol: float = 1e-5,
  1298. rtol: float = 1e-3,
  1299. gen_non_contig_grad_outputs: bool = False,
  1300. raise_exception: bool = True,
  1301. nondet_tol: float = 0.0,
  1302. check_undefined_grad: bool = True,
  1303. check_grad_dtypes: bool = False,
  1304. check_batched_grad: bool = False,
  1305. check_fwd_over_rev: bool = False,
  1306. check_rev_over_rev: bool = True,
  1307. fast_mode: bool = False,
  1308. ) -> bool:
  1309. r"""Check gradients of gradients computed via small finite differences
  1310. against analytical gradients w.r.t. tensors in :attr:`inputs` and
  1311. :attr:`grad_outputs` that are of floating point or complex type and with
  1312. ``requires_grad=True``.
  1313. This function checks that backpropagating through the gradients computed
  1314. to the given :attr:`grad_outputs` are correct.
  1315. The check between numerical and analytical gradients uses :func:`~torch.allclose`.
  1316. .. note::
  1317. The default values are designed for :attr:`input` and
  1318. :attr:`grad_outputs` of double precision. This check will likely fail if
  1319. they are of less precision, e.g., ``FloatTensor``.
  1320. .. warning::
  1321. If any checked tensor in :attr:`input` and :attr:`grad_outputs` has
  1322. overlapping memory, i.e., different indices pointing to the same memory
  1323. address (e.g., from :func:`torch.expand`), this check will likely fail
  1324. because the numerical gradients computed by point perturbation at such
  1325. indices will change values at all other indices that share the same
  1326. memory address.
  1327. Args:
  1328. func (function): a Python function that takes Tensor inputs and returns
  1329. a Tensor or a tuple of Tensors
  1330. inputs (tuple of Tensor or Tensor): inputs to the function
  1331. grad_outputs (tuple of Tensor or Tensor, optional): The gradients with
  1332. respect to the function's outputs.
  1333. eps (float, optional): perturbation for finite differences
  1334. atol (float, optional): absolute tolerance
  1335. rtol (float, optional): relative tolerance
  1336. gen_non_contig_grad_outputs (bool, optional): if :attr:`grad_outputs` is
  1337. ``None`` and :attr:`gen_non_contig_grad_outputs` is ``True``, the
  1338. randomly generated gradient outputs are made to be noncontiguous
  1339. raise_exception (bool, optional): indicating whether to raise an exception if
  1340. the check fails. The exception gives more information about the
  1341. exact nature of the failure. This is helpful when debugging gradchecks.
  1342. nondet_tol (float, optional): tolerance for non-determinism. When running
  1343. identical inputs through the differentiation, the results must either match
  1344. exactly (default, 0.0) or be within this tolerance. Note that a small amount
  1345. of nondeterminism in the gradient will lead to larger inaccuracies in
  1346. the second derivative.
  1347. check_undefined_grad (bool, optional): if True, check if undefined output grads
  1348. are supported and treated as zeros
  1349. check_batched_grad (bool, optional): if True, check if we can compute
  1350. batched gradients using prototype vmap support. Defaults to False.
  1351. fast_mode (bool, optional): if True, run a faster implementation of gradgradcheck that
  1352. no longer computes the entire jacobian.
  1353. Returns:
  1354. True if all differences satisfy allclose condition
  1355. """
  1356. assert check_fwd_over_rev or check_rev_over_rev, \
  1357. "Expected at least one of check_fwd_over_rev or check_rev_over_rev to be True"
  1358. assert not (check_undefined_grad and not check_rev_over_rev), \
  1359. "Setting check_undefined_grad=True requires check_rev_over_rev to be True"
  1360. assert not (check_batched_grad and not check_rev_over_rev), (
  1361. "Setting check_batched_grad=True requires check_rev_over_rev to be True")
  1362. # TODO: do we want to test this too?
  1363. # assert not (check_batched_forward_grad and not check_fwd_over_rev), (
  1364. # "Setting check_batched_forward_grad=True requires check_fwd_over_rev to be True")
  1365. tupled_inputs = _as_tuple(inputs)
  1366. if grad_outputs is None:
  1367. # If grad_outputs is not specified, create random Tensors of the same shape, type, and device as the outputs
  1368. outputs = _differentiable_outputs(func(*tupled_inputs))
  1369. tupled_grad_outputs = tuple(
  1370. torch.testing.make_tensor(
  1371. x.shape,
  1372. dtype=x.dtype if x.is_floating_point() or x.is_complex() else torch.double,
  1373. device=x.device,
  1374. low=-1,
  1375. high=1,
  1376. requires_grad=True,
  1377. noncontiguous=gen_non_contig_grad_outputs,
  1378. )
  1379. for x in outputs
  1380. )
  1381. else:
  1382. tupled_grad_outputs = _as_tuple(grad_outputs)
  1383. num_outputs = len(tupled_grad_outputs)
  1384. # NB: We need to save the requires_grad information about the inputs here because gradcheck detaches inputs
  1385. # before running forward mode AD
  1386. diff_input_args_indices = {i for i, x in enumerate(tupled_inputs) if is_tensor_like(x) and x.requires_grad}
  1387. diff_grad_output_indices = {i for i, x in enumerate(tupled_grad_outputs) if x.requires_grad}
  1388. def new_func(*args):
  1389. # Restore the requires_grad information
  1390. input_args = tuple(x.requires_grad_() if i in diff_input_args_indices else x for i, x in enumerate(args[:-num_outputs]))
  1391. outputs = _differentiable_outputs(func(*input_args))
  1392. grad_outputs = tuple(x.requires_grad_() if i in diff_grad_output_indices else x for i, x in enumerate(args[-num_outputs:]))
  1393. diff_input_args = tuple(x for i, x in enumerate(input_args) if i in diff_input_args_indices)
  1394. grad_inputs = torch.autograd.grad(outputs, diff_input_args, grad_outputs, create_graph=True,
  1395. allow_unused=True)
  1396. grad_inputs = tuple(g for g in grad_inputs if g is not None)
  1397. return grad_inputs
  1398. return gradcheck(
  1399. new_func, tupled_inputs + tupled_grad_outputs, eps=eps, atol=atol, rtol=rtol, raise_exception=raise_exception,
  1400. nondet_tol=nondet_tol, check_undefined_grad=check_undefined_grad,
  1401. check_grad_dtypes=check_grad_dtypes, check_batched_grad=check_batched_grad, fast_mode=fast_mode,
  1402. check_forward_ad=check_fwd_over_rev, check_backward_ad=check_rev_over_rev)