gradcheck.py 77 KB

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