functional.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. import torch
  2. from typing import Tuple, List
  3. from . import forward_ad as fwAD
  4. from torch._vmap_internals import _vmap
  5. # Utility functions
  6. def _as_tuple_nocheck(x):
  7. if isinstance(x, tuple):
  8. return x
  9. elif isinstance(x, list):
  10. return tuple(x)
  11. else:
  12. return x,
  13. def _as_tuple(inp, arg_name=None, fn_name=None):
  14. # Ensures that inp is a tuple of Tensors
  15. # Returns whether or not the original inp was a tuple and the tupled version of the input
  16. if arg_name is None and fn_name is None:
  17. return _as_tuple_nocheck(inp)
  18. is_inp_tuple = True
  19. if not isinstance(inp, tuple):
  20. inp = (inp,)
  21. is_inp_tuple = False
  22. for i, el in enumerate(inp):
  23. if not isinstance(el, torch.Tensor):
  24. if is_inp_tuple:
  25. raise TypeError("The {} given to {} must be either a Tensor or a tuple of Tensors but the"
  26. " value at index {} has type {}.".format(arg_name, fn_name, i, type(el)))
  27. else:
  28. raise TypeError("The {} given to {} must be either a Tensor or a tuple of Tensors but the"
  29. " given {} has type {}.".format(arg_name, fn_name, arg_name, type(el)))
  30. return is_inp_tuple, inp
  31. def _tuple_postprocess(res, to_unpack):
  32. # Unpacks a potentially nested tuple of Tensors
  33. # to_unpack should be a single boolean or a tuple of two booleans.
  34. # It is used to:
  35. # - invert _as_tuple when res should match the inp given to _as_tuple
  36. # - optionally remove nesting of two tuples created by multiple calls to _as_tuple
  37. if isinstance(to_unpack, tuple):
  38. assert len(to_unpack) == 2
  39. if not to_unpack[1]:
  40. res = tuple(el[0] for el in res)
  41. if not to_unpack[0]:
  42. res = res[0]
  43. else:
  44. if not to_unpack:
  45. res = res[0]
  46. return res
  47. def _grad_preprocess(inputs, create_graph, need_graph):
  48. # Preprocess the inputs to make sure they require gradient
  49. # inputs is a tuple of Tensors to preprocess
  50. # create_graph specifies if the user wants gradients to flow back to the Tensors in inputs
  51. # need_graph specifies if we internally want gradients to flow back to the Tensors in res
  52. # Note that we *always* create a new Tensor object to be able to see the difference between
  53. # inputs given as arguments and the same Tensors automatically captured by the user function.
  54. # Check this issue for more details on how that can happen: https://github.com/pytorch/pytorch/issues/32576
  55. res = []
  56. for inp in inputs:
  57. if create_graph and inp.requires_grad:
  58. # Create at least a new Tensor object in a differentiable way
  59. if not inp.is_sparse:
  60. # Use .view_as() to get a shallow copy
  61. res.append(inp.view_as(inp))
  62. else:
  63. # We cannot use view for sparse Tensors so we clone
  64. res.append(inp.clone())
  65. else:
  66. res.append(inp.detach().requires_grad_(need_graph))
  67. return tuple(res)
  68. def _grad_postprocess(inputs, create_graph):
  69. # Postprocess the generated Tensors to avoid returning Tensors with history when the user did not
  70. # request it.
  71. if isinstance(inputs[0], torch.Tensor):
  72. if not create_graph:
  73. return tuple(inp.detach() for inp in inputs)
  74. else:
  75. return inputs
  76. else:
  77. return tuple(_grad_postprocess(inp, create_graph) for inp in inputs)
  78. def _validate_v(v, other, is_other_tuple):
  79. # This assumes that other is the correct shape, and v should match
  80. # Both are assumed to be tuples of Tensors
  81. if len(other) != len(v):
  82. if is_other_tuple:
  83. raise RuntimeError("v is a tuple of invalid length: should be {} but got {}.".format(len(other), len(v)))
  84. else:
  85. raise RuntimeError("The given v should contain a single Tensor.")
  86. for idx, (el_v, el_other) in enumerate(zip(v, other)):
  87. if el_v.size() != el_other.size():
  88. prepend = ""
  89. if is_other_tuple:
  90. prepend = "Entry {} in ".format(idx)
  91. raise RuntimeError("{}v has invalid size: should be {} but got {}.".format(
  92. prepend, el_other.size(), el_v.size()))
  93. def _check_requires_grad(inputs, input_type, strict):
  94. # Used to make all the necessary checks to raise nice errors in strict mode.
  95. if not strict:
  96. return
  97. if input_type not in ["outputs", "grad_inputs", "jacobian", "hessian"]:
  98. raise RuntimeError("Invalid input_type to _check_requires_grad")
  99. for i, inp in enumerate(inputs):
  100. if inp is None:
  101. # This can only be reached for grad_inputs.
  102. raise RuntimeError("The output of the user-provided function is independent of input {}."
  103. " This is not allowed in strict mode.".format(i))
  104. if not inp.requires_grad:
  105. if input_type == "hessian":
  106. raise RuntimeError("The hessian of the user-provided function with respect to input {}"
  107. " is independent of the input. This is not allowed in strict mode."
  108. " You should ensure that your function is thrice differentiable and that"
  109. " the hessian depends on the inputs.".format(i))
  110. elif input_type == "jacobian":
  111. raise RuntimeError("While computing the hessian, found that the jacobian of the user-provided"
  112. " function with respect to input {} is independent of the input. This is not"
  113. " allowed in strict mode. You should ensure that your function is twice"
  114. " differentiable and that the jacobian depends on the inputs (this would be"
  115. " violated by a linear function for example).".format(i))
  116. elif input_type == "grad_inputs":
  117. raise RuntimeError("The gradient with respect to input {} is independent of the inputs of the"
  118. " user-provided function. This is not allowed in strict mode.".format(i))
  119. else:
  120. raise RuntimeError("Output {} of the user-provided function does not require gradients."
  121. " The outputs must be computed in a differentiable manner from the input"
  122. " when running in strict mode.".format(i))
  123. def _autograd_grad(outputs, inputs, grad_outputs=None, create_graph=False, retain_graph=None, is_grads_batched=False):
  124. # Version of autograd.grad that accepts `None` in outputs and do not compute gradients for them.
  125. # This has the extra constraint that inputs has to be a tuple
  126. assert isinstance(outputs, tuple)
  127. if grad_outputs is None:
  128. grad_outputs = (None,) * len(outputs)
  129. assert isinstance(grad_outputs, tuple)
  130. assert len(outputs) == len(grad_outputs)
  131. new_outputs: Tuple[torch.Tensor, ...] = tuple()
  132. new_grad_outputs: Tuple[torch.Tensor, ...] = tuple()
  133. for out, grad_out in zip(outputs, grad_outputs):
  134. if out is not None and out.requires_grad:
  135. new_outputs += (out,)
  136. new_grad_outputs += (grad_out,)
  137. if len(new_outputs) == 0:
  138. # No differentiable output, we don't need to call the autograd engine
  139. return (None,) * len(inputs)
  140. else:
  141. return torch.autograd.grad(new_outputs, inputs, new_grad_outputs, allow_unused=True,
  142. create_graph=create_graph, retain_graph=retain_graph,
  143. is_grads_batched=is_grads_batched)
  144. def _fill_in_zeros(grads, refs, strict, create_graph, stage):
  145. # Used to detect None in the grads and depending on the flags, either replace them
  146. # with Tensors full of 0s of the appropriate size based on the refs or raise an error.
  147. # strict and create graph allow us to detect when it is appropriate to raise an error
  148. # stage gives us information of which backward call we consider to give good error message
  149. if stage not in ["back", "back_trick", "double_back", "double_back_trick"]:
  150. raise RuntimeError("Invalid stage argument '{}' to _fill_in_zeros".format(stage))
  151. res: Tuple[torch.Tensor, ...] = tuple()
  152. for i, grads_i in enumerate(grads):
  153. if grads_i is None:
  154. if strict:
  155. if stage == "back":
  156. raise RuntimeError("The output of the user-provided function is independent of "
  157. "input {}. This is not allowed in strict mode.".format(i))
  158. elif stage == "back_trick":
  159. raise RuntimeError("The gradient with respect to the input is independent of entry {}"
  160. " in the grad_outputs when using the double backward trick to compute"
  161. " forward mode gradients. This is not allowed in strict mode.".format(i))
  162. elif stage == "double_back":
  163. raise RuntimeError("The jacobian of the user-provided function is independent of "
  164. "input {}. This is not allowed in strict mode.".format(i))
  165. else:
  166. raise RuntimeError("The hessian of the user-provided function is independent of "
  167. "entry {} in the grad_jacobian. This is not allowed in strict "
  168. "mode as it prevents from using the double backward trick to "
  169. "replace forward mode AD.".format(i))
  170. grads_i = torch.zeros_like(refs[i])
  171. else:
  172. if strict and create_graph and not grads_i.requires_grad:
  173. if "double" not in stage:
  174. raise RuntimeError("The jacobian of the user-provided function is independent of "
  175. "input {}. This is not allowed in strict mode when create_graph=True.".format(i))
  176. else:
  177. raise RuntimeError("The hessian of the user-provided function is independent of "
  178. "input {}. This is not allowed in strict mode when create_graph=True.".format(i))
  179. res += (grads_i,)
  180. return res
  181. # Public API
  182. def vjp(func, inputs, v=None, create_graph=False, strict=False):
  183. r"""Function that computes the dot product between a vector ``v`` and the
  184. Jacobian of the given function at the point given by the inputs.
  185. Args:
  186. func (function): a Python function that takes Tensor inputs and returns
  187. a tuple of Tensors or a Tensor.
  188. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  189. v (tuple of Tensors or Tensor): The vector for which the vector
  190. Jacobian product is computed. Must be the same size as the output
  191. of ``func``. This argument is optional when the output of ``func``
  192. contains a single element and (if it is not provided) will be set
  193. as a Tensor containing a single ``1``.
  194. create_graph (bool, optional): If ``True``, both the output and result
  195. will be computed in a differentiable way. Note that when ``strict``
  196. is ``False``, the result can not require gradients or be
  197. disconnected from the inputs. Defaults to ``False``.
  198. strict (bool, optional): If ``True``, an error will be raised when we
  199. detect that there exists an input such that all the outputs are
  200. independent of it. If ``False``, we return a Tensor of zeros as the
  201. vjp for said inputs, which is the expected mathematical value.
  202. Defaults to ``False``.
  203. Returns:
  204. output (tuple): tuple with:
  205. func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
  206. vjp (tuple of Tensors or Tensor): result of the dot product with
  207. the same shape as the inputs.
  208. Example:
  209. >>> def exp_reducer(x):
  210. ... return x.exp().sum(dim=1)
  211. >>> inputs = torch.rand(4, 4)
  212. >>> v = torch.ones(4)
  213. >>> vjp(exp_reducer, inputs, v)
  214. (tensor([5.7817, 7.2458, 5.7830, 6.7782]),
  215. tensor([[1.4458, 1.3962, 1.3042, 1.6354],
  216. [2.1288, 1.0652, 1.5483, 2.5035],
  217. [2.2046, 1.1292, 1.1432, 1.3059],
  218. [1.3225, 1.6652, 1.7753, 2.0152]]))
  219. >>> vjp(exp_reducer, inputs, v, create_graph=True)
  220. (tensor([5.7817, 7.2458, 5.7830, 6.7782], grad_fn=<SumBackward1>),
  221. tensor([[1.4458, 1.3962, 1.3042, 1.6354],
  222. [2.1288, 1.0652, 1.5483, 2.5035],
  223. [2.2046, 1.1292, 1.1432, 1.3059],
  224. [1.3225, 1.6652, 1.7753, 2.0152]], grad_fn=<MulBackward0>))
  225. >>> def adder(x, y):
  226. ... return 2 * x + 3 * y
  227. >>> inputs = (torch.rand(2), torch.rand(2))
  228. >>> v = torch.ones(2)
  229. >>> vjp(adder, inputs, v)
  230. (tensor([2.4225, 2.3340]),
  231. (tensor([2., 2.]), tensor([3., 3.])))
  232. """
  233. with torch.enable_grad():
  234. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "vjp")
  235. inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
  236. outputs = func(*inputs)
  237. is_outputs_tuple, outputs = _as_tuple(outputs, "outputs of the user-provided function", "vjp")
  238. _check_requires_grad(outputs, "outputs", strict=strict)
  239. if v is not None:
  240. _, v = _as_tuple(v, "v", "vjp")
  241. v = _grad_preprocess(v, create_graph=create_graph, need_graph=False)
  242. _validate_v(v, outputs, is_outputs_tuple)
  243. else:
  244. if len(outputs) != 1 or outputs[0].nelement() != 1:
  245. raise RuntimeError("The vector v can only be None if the "
  246. "user-provided function returns "
  247. "a single Tensor with a single element.")
  248. enable_grad = True if create_graph else torch.is_grad_enabled()
  249. with torch.set_grad_enabled(enable_grad):
  250. grad_res = _autograd_grad(outputs, inputs, v, create_graph=create_graph)
  251. vjp = _fill_in_zeros(grad_res, inputs, strict, create_graph, "back")
  252. # Cleanup objects and return them to the user
  253. outputs = _grad_postprocess(outputs, create_graph)
  254. vjp = _grad_postprocess(vjp, create_graph)
  255. return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(vjp, is_inputs_tuple)
  256. def jvp(func, inputs, v=None, create_graph=False, strict=False):
  257. r"""Function that computes the dot product between the Jacobian of
  258. the given function at the point given by the inputs and a vector ``v``.
  259. Args:
  260. func (function): a Python function that takes Tensor inputs and returns
  261. a tuple of Tensors or a Tensor.
  262. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  263. v (tuple of Tensors or Tensor): The vector for which the Jacobian
  264. vector product is computed. Must be the same size as the input of
  265. ``func``. This argument is optional when the input to ``func``
  266. contains a single element and (if it is not provided) will be set
  267. as a Tensor containing a single ``1``.
  268. create_graph (bool, optional): If ``True``, both the output and result
  269. will be computed in a differentiable way. Note that when ``strict``
  270. is ``False``, the result can not require gradients or be
  271. disconnected from the inputs. Defaults to ``False``.
  272. strict (bool, optional): If ``True``, an error will be raised when we
  273. detect that there exists an input such that all the outputs are
  274. independent of it. If ``False``, we return a Tensor of zeros as the
  275. jvp for said inputs, which is the expected mathematical value.
  276. Defaults to ``False``.
  277. Returns:
  278. output (tuple): tuple with:
  279. func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
  280. jvp (tuple of Tensors or Tensor): result of the dot product with
  281. the same shape as the output.
  282. Note:
  283. ``autograd.functional.jvp`` computes the jvp by using the backward of
  284. the backward (sometimes called the double backwards trick). This is not
  285. the most performant way of computing the jvp. Please consider using
  286. `functorch's jvp <https://github.com/pytorch/functorch#jvp>`_
  287. or the :ref:`low-level forward-mode AD API <forward-mode-ad>` instead.
  288. Example:
  289. >>> def exp_reducer(x):
  290. ... return x.exp().sum(dim=1)
  291. >>> inputs = torch.rand(4, 4)
  292. >>> v = torch.ones(4, 4)
  293. >>> jvp(exp_reducer, inputs, v)
  294. (tensor([6.3090, 4.6742, 7.9114, 8.2106]),
  295. tensor([6.3090, 4.6742, 7.9114, 8.2106]))
  296. >>> jvp(exp_reducer, inputs, v, create_graph=True)
  297. (tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SumBackward1>),
  298. tensor([6.3090, 4.6742, 7.9114, 8.2106], grad_fn=<SqueezeBackward1>))
  299. >>> def adder(x, y):
  300. ... return 2 * x + 3 * y
  301. >>> inputs = (torch.rand(2), torch.rand(2))
  302. >>> v = (torch.ones(2), torch.ones(2))
  303. >>> jvp(adder, inputs, v)
  304. (tensor([2.2399, 2.5005]),
  305. tensor([5., 5.]))
  306. """
  307. with torch.enable_grad():
  308. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "jvp")
  309. inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
  310. if v is not None:
  311. _, v = _as_tuple(v, "v", "jvp")
  312. v = _grad_preprocess(v, create_graph=create_graph, need_graph=False)
  313. _validate_v(v, inputs, is_inputs_tuple)
  314. else:
  315. if len(inputs) != 1 or inputs[0].nelement() != 1:
  316. raise RuntimeError("The vector v can only be None if the input to "
  317. "the user-provided function is a single Tensor "
  318. "with a single element.")
  319. outputs = func(*inputs)
  320. is_outputs_tuple, outputs = _as_tuple(outputs, "outputs of the user-provided function", "jvp")
  321. _check_requires_grad(outputs, "outputs", strict=strict)
  322. # The backward is linear so the value of grad_outputs is not important as
  323. # it won't appear in the double backward graph. We only need to ensure that
  324. # it does not contain inf or nan.
  325. grad_outputs = tuple(torch.zeros_like(out, requires_grad=True) for out in outputs)
  326. grad_inputs = _autograd_grad(outputs, inputs, grad_outputs, create_graph=True)
  327. _check_requires_grad(grad_inputs, "grad_inputs", strict=strict)
  328. if create_graph:
  329. with torch.enable_grad():
  330. grad_res = _autograd_grad(grad_inputs, grad_outputs, v, create_graph=create_graph)
  331. jvp = _fill_in_zeros(grad_res, outputs, strict, create_graph, "back_trick")
  332. else:
  333. grad_res = _autograd_grad(grad_inputs, grad_outputs, v, create_graph=create_graph)
  334. jvp = _fill_in_zeros(grad_res, outputs, strict, create_graph, "back_trick")
  335. # Cleanup objects and return them to the user
  336. outputs = _grad_postprocess(outputs, create_graph)
  337. jvp = _grad_postprocess(jvp, create_graph)
  338. return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(jvp, is_outputs_tuple)
  339. def _construct_standard_basis_for(tensors: Tuple[torch.Tensor, ...], tensor_numels: Tuple[int, ...]) -> Tuple[torch.Tensor, ...]:
  340. # This function:
  341. # - constructs a N=sum(tensor_numels) standard basis. i.e. an NxN identity matrix.
  342. # - Splits the identity matrix into chunks with each chunk size determined by `tensor_numels`.
  343. # - Each chunk corresponds to one tensor. The chunk has the same dtype and
  344. # device as the tensor
  345. #
  346. # For example, with tensor_numels = [1, 2, 1], this function returns:
  347. # ( tensor([[1], tensor([[0, 0], tensor([[0],
  348. # [0], [1, 0], [0],
  349. # [0], [0, 1], [0],
  350. # [0]]) , [0, 0]]) , [1]]) )
  351. #
  352. # Precondition: tensor_numels == tuple(tensor.numel() for tensor in tensors)
  353. # Precondition: tensors always has at least one element.
  354. #
  355. # See NOTE: [Computing jacobian with vmap and grad for multiple tensors]
  356. # for context behind this function. All the pre-conditions are guarded for
  357. # in torch.autograd.functional.jacobian.
  358. assert len(tensors) == len(tensor_numels)
  359. assert len(tensors) > 0
  360. total_numel = sum(tensor_numels)
  361. chunks = tuple(tensor.new_zeros(total_numel, tensor_numel)
  362. for tensor, tensor_numel in zip(tensors, tensor_numels))
  363. diag_start_idx = 0
  364. for chunk, numel in zip(chunks, tensor_numels):
  365. chunk.diagonal(diag_start_idx).fill_(1)
  366. diag_start_idx -= numel
  367. return chunks
  368. def _jacfwd(func, inputs, strict=False, vectorize=False):
  369. if strict:
  370. raise RuntimeError('torch.autograd.functional.jacobian: `strict=True` '
  371. 'and `strategy="forward-mode"` are not supported together (yet). '
  372. 'Please either set `strict=False` or '
  373. '`strategy="reverse-mode"`.')
  374. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "jacobian")
  375. output_info = []
  376. if vectorize:
  377. # See NOTE: [Computing jacobian with vmap and grad for multiple outputs]
  378. input_numels = tuple(input.numel() for input in inputs)
  379. # Step 1: Prepare tangents
  380. tangents = _construct_standard_basis_for(inputs, input_numels)
  381. # Step 2: Compute vmap over computation with dual tensors
  382. def jvp(tangents):
  383. with fwAD.dual_level():
  384. dual_inputs = tuple(
  385. fwAD.make_dual(input, tangent.view_as(input)) for input, tangent in zip(inputs, tangents))
  386. _is_outputs_tuple, dual_outputs = _as_tuple(func(*dual_inputs), "outputs")
  387. output_info.append(_is_outputs_tuple)
  388. jv = []
  389. primal_outs = []
  390. for dual_out in dual_outputs:
  391. primal, tangent = fwAD.unpack_dual(dual_out)
  392. primal_outs.append(primal)
  393. if tangent is not None:
  394. jv.append(tangent)
  395. else:
  396. jv.append(torch.zeros_like(primal))
  397. output_info.append(primal_outs)
  398. return tuple(jv)
  399. outputs_before_split = _vmap(jvp)(tangents)
  400. is_outputs_tuple, outputs = output_info
  401. # Step 3: for each of the output tangents, split along dim 0
  402. jacobian_input_output = []
  403. for jac, output_i in zip(outputs_before_split, outputs):
  404. jacobian_output_i_output = []
  405. for jac, input_j in zip(jac.split(input_numels, dim=0), inputs):
  406. # We need to transpose the Jacobian because in forward AD, the
  407. # batch dimension represents that of the inputs
  408. jacobian_input_i_output_j = jac.permute(*range(1, jac.ndim), 0) \
  409. .reshape(tuple([*output_i.shape, *input_j.shape])) # noqa: C409
  410. jacobian_output_i_output.append(jacobian_input_i_output_j)
  411. jacobian_input_output.append(jacobian_output_i_output)
  412. # Omit [Step 4] because everything is already transposed w/ forward AD
  413. return _tuple_postprocess(jacobian_input_output, (is_outputs_tuple, is_inputs_tuple))
  414. else:
  415. raise NotImplementedError("Computing Jacobian using forward-AD or forward-over-reverse Hessian is"
  416. "only implemented for `vectorize=True`.")
  417. def jacobian(func, inputs, create_graph=False, strict=False, vectorize=False, strategy="reverse-mode"):
  418. r"""Function that computes the Jacobian of a given function.
  419. Args:
  420. func (function): a Python function that takes Tensor inputs and returns
  421. a tuple of Tensors or a Tensor.
  422. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  423. create_graph (bool, optional): If ``True``, the Jacobian will be
  424. computed in a differentiable manner. Note that when ``strict`` is
  425. ``False``, the result can not require gradients or be disconnected
  426. from the inputs. Defaults to ``False``.
  427. strict (bool, optional): If ``True``, an error will be raised when we
  428. detect that there exists an input such that all the outputs are
  429. independent of it. If ``False``, we return a Tensor of zeros as the
  430. jacobian for said inputs, which is the expected mathematical value.
  431. Defaults to ``False``.
  432. vectorize (bool, optional): This feature is experimental.
  433. Please consider using
  434. `functorch's jacrev or jacfwd <https://github.com/pytorch/functorch#what-are-the-transforms>`_
  435. instead if you are looking for something less experimental and more performant.
  436. When computing the jacobian, usually we invoke
  437. ``autograd.grad`` once per row of the jacobian. If this flag is
  438. ``True``, we perform only a single ``autograd.grad`` call with
  439. ``batched_grad=True`` which uses the vmap prototype feature.
  440. Though this should lead to performance improvements in many cases,
  441. because this feature is still experimental, there may be performance
  442. cliffs. See :func:`torch.autograd.grad`'s ``batched_grad`` parameter for
  443. more information.
  444. strategy (str, optional): Set to ``"forward-mode"`` or ``"reverse-mode"`` to
  445. determine whether the Jacobian will be computed with forward or reverse
  446. mode AD. Currently, ``"forward-mode"`` requires ``vectorized=True``.
  447. Defaults to ``"reverse-mode"``. If ``func`` has more outputs than
  448. inputs, ``"forward-mode"`` tends to be more performant. Otherwise,
  449. prefer to use ``"reverse-mode"``.
  450. Returns:
  451. Jacobian (Tensor or nested tuple of Tensors): if there is a single
  452. input and output, this will be a single Tensor containing the
  453. Jacobian for the linearized inputs and output. If one of the two is
  454. a tuple, then the Jacobian will be a tuple of Tensors. If both of
  455. them are tuples, then the Jacobian will be a tuple of tuple of
  456. Tensors where ``Jacobian[i][j]`` will contain the Jacobian of the
  457. ``i``\th output and ``j``\th input and will have as size the
  458. concatenation of the sizes of the corresponding output and the
  459. corresponding input and will have same dtype and device as the
  460. corresponding input. If strategy is ``forward-mode``, the dtype will be
  461. that of the output; otherwise, the input.
  462. Example:
  463. >>> def exp_reducer(x):
  464. ... return x.exp().sum(dim=1)
  465. >>> inputs = torch.rand(2, 2)
  466. >>> jacobian(exp_reducer, inputs)
  467. tensor([[[1.4917, 2.4352],
  468. [0.0000, 0.0000]],
  469. [[0.0000, 0.0000],
  470. [2.4369, 2.3799]]])
  471. >>> jacobian(exp_reducer, inputs, create_graph=True)
  472. tensor([[[1.4917, 2.4352],
  473. [0.0000, 0.0000]],
  474. [[0.0000, 0.0000],
  475. [2.4369, 2.3799]]], grad_fn=<ViewBackward>)
  476. >>> def exp_adder(x, y):
  477. ... return 2 * x.exp() + 3 * y
  478. >>> inputs = (torch.rand(2), torch.rand(2))
  479. >>> jacobian(exp_adder, inputs)
  480. (tensor([[2.8052, 0.0000],
  481. [0.0000, 3.3963]]),
  482. tensor([[3., 0.],
  483. [0., 3.]]))
  484. """
  485. assert strategy in ("forward-mode", "reverse-mode"), (
  486. 'Expected strategy to be either "forward-mode" or "reverse-mode". Hint: If your '
  487. 'function has more outputs than inputs, "forward-mode" tends to be more performant. '
  488. 'Otherwise, prefer to use "reverse-mode".')
  489. if strategy == "forward-mode":
  490. if create_graph:
  491. raise NotImplementedError('torch.autograd.functional.jacobian: `create_graph=True` '
  492. 'and `strategy="forward-mode"` are not supported together (yet). '
  493. 'Please either set `create_graph=False` or '
  494. '`strategy="reverse-mode"`.')
  495. return _jacfwd(func, inputs, strict, vectorize)
  496. with torch.enable_grad():
  497. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "jacobian")
  498. inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
  499. outputs = func(*inputs)
  500. is_outputs_tuple, outputs = _as_tuple(outputs,
  501. "outputs of the user-provided function",
  502. "jacobian")
  503. _check_requires_grad(outputs, "outputs", strict=strict)
  504. if vectorize:
  505. if strict:
  506. raise RuntimeError('torch.autograd.functional.jacobian: `strict=True` '
  507. 'and `vectorized=True` are not supported together. '
  508. 'Please either set `strict=False` or '
  509. '`vectorize=False`.')
  510. # NOTE: [Computing jacobian with vmap and grad for multiple outputs]
  511. #
  512. # Let's consider f(x) = (x**2, x.sum()) and let x = torch.randn(3).
  513. # It turns out we can compute the jacobian of this function with a single
  514. # call to autograd.grad by using vmap over the correct grad_outputs.
  515. #
  516. # Firstly, one way to compute the jacobian is to stack x**2 and x.sum()
  517. # into a 4D vector. E.g., use g(x) = torch.stack([x**2, x.sum()])
  518. #
  519. # To get the first row of the jacobian, we call
  520. # >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([1, 0, 0, 0]))
  521. # To get the 2nd row of the jacobian, we call
  522. # >>> autograd.grad(g(x), x, grad_outputs=torch.tensor([0, 1, 0, 0]))
  523. # and so on.
  524. #
  525. # Using vmap, we can vectorize all 4 of these computations into one by
  526. # passing the standard basis for R^4 as the grad_output.
  527. # vmap(partial(autograd.grad, g(x), x))(torch.eye(4)).
  528. #
  529. # Now, how do we compute the jacobian *without stacking the output*?
  530. # We can just split the standard basis across the outputs. So to
  531. # compute the jacobian of f(x), we'd use
  532. # >>> autograd.grad(f(x), x, grad_outputs=_construct_standard_basis_for(...))
  533. # The grad_outputs looks like the following:
  534. # ( torch.tensor([[1, 0, 0],
  535. # [0, 1, 0],
  536. # [0, 0, 1],
  537. # [0, 0, 0]]),
  538. # torch.tensor([[0],
  539. # [0],
  540. # [0],
  541. # [1]]) )
  542. #
  543. # But we're not done yet!
  544. # >>> vmap(partial(autograd.grad(f(x), x, grad_outputs=...)))
  545. # returns a Tensor of shape [4, 3]. We have to remember to split the
  546. # jacobian of shape [4, 3] into two:
  547. # - one of shape [3, 3] for the first output
  548. # - one of shape [ 3] for the second output
  549. # Step 1: Construct grad_outputs by splitting the standard basis
  550. output_numels = tuple(output.numel() for output in outputs)
  551. grad_outputs = _construct_standard_basis_for(outputs, output_numels)
  552. flat_outputs = tuple(output.reshape(-1) for output in outputs)
  553. # Step 2: Call vmap + autograd.grad
  554. def vjp(grad_output):
  555. vj = list(_autograd_grad(flat_outputs, inputs, grad_output, create_graph=create_graph, is_grads_batched=True))
  556. for el_idx, vj_el in enumerate(vj):
  557. if vj_el is not None:
  558. continue
  559. vj[el_idx] = torch.zeros_like(inputs[el_idx]).expand((sum(output_numels),) + inputs[el_idx].shape)
  560. return tuple(vj)
  561. jacobians_of_flat_output = vjp(grad_outputs)
  562. # Step 3: The returned jacobian is one big tensor per input. In this step,
  563. # we split each Tensor by output.
  564. jacobian_input_output = []
  565. for jac, input_i in zip(jacobians_of_flat_output, inputs):
  566. jacobian_input_i_output = []
  567. for jac, output_j in zip(jac.split(output_numels, dim=0), outputs):
  568. jacobian_input_i_output_j = jac.view(output_j.shape + input_i.shape)
  569. jacobian_input_i_output.append(jacobian_input_i_output_j)
  570. jacobian_input_output.append(jacobian_input_i_output)
  571. # Step 4: Right now, `jacobian` is a List[List[Tensor]].
  572. # The outer List corresponds to the number of inputs,
  573. # the inner List corresponds to the number of outputs.
  574. # We need to exchange the order of these and convert to tuples
  575. # before returning.
  576. jacobian_output_input = tuple(zip(*jacobian_input_output))
  577. jacobian_output_input = _grad_postprocess(jacobian_output_input, create_graph)
  578. return _tuple_postprocess(jacobian_output_input, (is_outputs_tuple, is_inputs_tuple))
  579. jacobian: Tuple[torch.Tensor, ...] = tuple()
  580. for i, out in enumerate(outputs):
  581. # mypy complains that expression and variable have different types due to the empty list
  582. jac_i: Tuple[List[torch.Tensor]] = tuple([] for _ in range(len(inputs))) # type: ignore[assignment]
  583. for j in range(out.nelement()):
  584. vj = _autograd_grad((out.reshape(-1)[j],), inputs,
  585. retain_graph=True, create_graph=create_graph)
  586. for el_idx, (jac_i_el, vj_el, inp_el) in enumerate(zip(jac_i, vj, inputs)):
  587. if vj_el is not None:
  588. if strict and create_graph and not vj_el.requires_grad:
  589. msg = ("The jacobian of the user-provided function is "
  590. "independent of input {}. This is not allowed in "
  591. "strict mode when create_graph=True.".format(i))
  592. raise RuntimeError(msg)
  593. jac_i_el.append(vj_el)
  594. else:
  595. if strict:
  596. msg = ("Output {} of the user-provided function is "
  597. "independent of input {}. This is not allowed in "
  598. "strict mode.".format(i, el_idx))
  599. raise RuntimeError(msg)
  600. jac_i_el.append(torch.zeros_like(inp_el))
  601. jacobian += (tuple(torch.stack(jac_i_el, dim=0).view(out.size() # type: ignore[operator]
  602. + inputs[el_idx].size()) for (el_idx, jac_i_el) in enumerate(jac_i)), )
  603. jacobian = _grad_postprocess(jacobian, create_graph)
  604. return _tuple_postprocess(jacobian, (is_outputs_tuple, is_inputs_tuple))
  605. def hessian(func, inputs, create_graph=False, strict=False, vectorize=False, outer_jacobian_strategy="reverse-mode"):
  606. r"""Function that computes the Hessian of a given scalar function.
  607. Args:
  608. func (function): a Python function that takes Tensor inputs and returns
  609. a Tensor with a single element.
  610. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  611. create_graph (bool, optional): If ``True``, the Hessian will be computed in
  612. a differentiable manner. Note that when ``strict`` is ``False``, the result can not
  613. require gradients or be disconnected from the inputs.
  614. Defaults to ``False``.
  615. strict (bool, optional): If ``True``, an error will be raised when we detect that there exists an input
  616. such that all the outputs are independent of it. If ``False``, we return a Tensor of zeros as the
  617. hessian for said inputs, which is the expected mathematical value.
  618. Defaults to ``False``.
  619. vectorize (bool, optional): This feature is experimental.
  620. Please consider using
  621. `functorch <https://github.com/pytorch/functorch#what-are-the-transforms>`_
  622. instead if you are looking for something less experimental and more performant.
  623. When computing the hessian, usually we invoke
  624. ``autograd.grad`` once per row of the hessian. If this flag is
  625. ``True``, we use the vmap prototype feature as the backend to
  626. vectorize calls to ``autograd.grad`` so we only invoke it once
  627. instead of once per row. This should lead to performance
  628. improvements in many use cases, however, due to this feature
  629. being incomplete, there may be performance cliffs. Please
  630. use `torch._C._debug_only_display_vmap_fallback_warnings(True)`
  631. to show any performance warnings and file us issues if
  632. warnings exist for your use case. Defaults to ``False``.
  633. outer_jacobian_strategy (str, optional): The Hessian is computed by
  634. computing the Jacobian of a Jacobian. The inner Jacobian is always
  635. computed in reverse-mode AD. Setting strategy to ``"forward-mode"``
  636. or ``"reverse-mode"`` determines whether the outer Jacobian will be
  637. computed with forward or reverse mode AD. Currently, computing the outer
  638. Jacobian in ``"forward-mode"`` requires ``vectorized=True``. Defaults
  639. to ``"reverse-mode"``.
  640. Returns:
  641. Hessian (Tensor or a tuple of tuple of Tensors): if there is a single input,
  642. this will be a single Tensor containing the Hessian for the input.
  643. If it is a tuple, then the Hessian will be a tuple of tuples where
  644. ``Hessian[i][j]`` will contain the Hessian of the ``i``\th input
  645. and ``j``\th input with size the sum of the size of the ``i``\th input plus
  646. the size of the ``j``\th input. ``Hessian[i][j]`` will have the same
  647. dtype and device as the corresponding ``i``\th input.
  648. Example:
  649. >>> def pow_reducer(x):
  650. ... return x.pow(3).sum()
  651. >>> inputs = torch.rand(2, 2)
  652. >>> hessian(pow_reducer, inputs)
  653. tensor([[[[5.2265, 0.0000],
  654. [0.0000, 0.0000]],
  655. [[0.0000, 4.8221],
  656. [0.0000, 0.0000]]],
  657. [[[0.0000, 0.0000],
  658. [1.9456, 0.0000]],
  659. [[0.0000, 0.0000],
  660. [0.0000, 3.2550]]]])
  661. >>> hessian(pow_reducer, inputs, create_graph=True)
  662. tensor([[[[5.2265, 0.0000],
  663. [0.0000, 0.0000]],
  664. [[0.0000, 4.8221],
  665. [0.0000, 0.0000]]],
  666. [[[0.0000, 0.0000],
  667. [1.9456, 0.0000]],
  668. [[0.0000, 0.0000],
  669. [0.0000, 3.2550]]]], grad_fn=<ViewBackward>)
  670. >>> def pow_adder_reducer(x, y):
  671. ... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
  672. >>> inputs = (torch.rand(2), torch.rand(2))
  673. >>> hessian(pow_adder_reducer, inputs)
  674. ((tensor([[4., 0.],
  675. [0., 4.]]),
  676. tensor([[0., 0.],
  677. [0., 0.]])),
  678. (tensor([[0., 0.],
  679. [0., 0.]]),
  680. tensor([[6., 0.],
  681. [0., 6.]])))
  682. """
  683. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "hessian")
  684. assert outer_jacobian_strategy in ("forward-mode", "reverse-mode"), (
  685. 'Expected strategy to be either "forward-mode" or "reverse-mode".')
  686. def ensure_single_output_function(*inp):
  687. out = func(*inp)
  688. is_out_tuple, t_out = _as_tuple(out, "outputs of the user-provided function", "hessian")
  689. _check_requires_grad(t_out, "outputs", strict=strict)
  690. if is_out_tuple or not isinstance(out, torch.Tensor):
  691. raise RuntimeError("The function given to hessian should return a single Tensor")
  692. if out.nelement() != 1:
  693. raise RuntimeError("The Tensor returned by the function given to hessian should contain a single element")
  694. return out.squeeze()
  695. def jac_func(*inp):
  696. if outer_jacobian_strategy == "forward-mode":
  697. # _grad_preprocess requires create_graph=True and input to require_grad
  698. # or else the input will be detached
  699. inp = tuple(t.requires_grad_(True) for t in inp)
  700. jac = jacobian(ensure_single_output_function, inp, create_graph=True)
  701. _check_requires_grad(jac, "jacobian", strict=strict)
  702. return jac
  703. res = jacobian(jac_func, inputs, create_graph=create_graph, strict=strict, vectorize=vectorize,
  704. strategy=outer_jacobian_strategy)
  705. return _tuple_postprocess(res, (is_inputs_tuple, is_inputs_tuple))
  706. def vhp(func, inputs, v=None, create_graph=False, strict=False):
  707. r"""Function that computes the dot product between a vector ``v`` and the
  708. Hessian of a given scalar function at the point given by the inputs.
  709. Args:
  710. func (function): a Python function that takes Tensor inputs and returns
  711. a Tensor with a single element.
  712. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  713. v (tuple of Tensors or Tensor): The vector for which the vector Hessian
  714. product is computed. Must be the same size as the input of
  715. ``func``. This argument is optional when ``func``'s input contains
  716. a single element and (if it is not provided) will be set as a
  717. Tensor containing a single ``1``.
  718. create_graph (bool, optional): If ``True``, both the output and result
  719. will be computed in a differentiable way. Note that when ``strict``
  720. is ``False``, the result can not require gradients or be
  721. disconnected from the inputs.
  722. Defaults to ``False``.
  723. strict (bool, optional): If ``True``, an error will be raised when we
  724. detect that there exists an input such that all the outputs are
  725. independent of it. If ``False``, we return a Tensor of zeros as the
  726. vhp for said inputs, which is the expected mathematical value.
  727. Defaults to ``False``.
  728. Returns:
  729. output (tuple): tuple with:
  730. func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
  731. vhp (tuple of Tensors or Tensor): result of the dot product with the
  732. same shape as the inputs.
  733. Example:
  734. >>> def pow_reducer(x):
  735. ... return x.pow(3).sum()
  736. >>> inputs = torch.rand(2, 2)
  737. >>> v = torch.ones(2, 2)
  738. >>> vhp(pow_reducer, inputs, v)
  739. (tensor(0.5591),
  740. tensor([[1.0689, 1.2431],
  741. [3.0989, 4.4456]]))
  742. >>> vhp(pow_reducer, inputs, v, create_graph=True)
  743. (tensor(0.5591, grad_fn=<SumBackward0>),
  744. tensor([[1.0689, 1.2431],
  745. [3.0989, 4.4456]], grad_fn=<MulBackward0>))
  746. >>> def pow_adder_reducer(x, y):
  747. ... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
  748. >>> inputs = (torch.rand(2), torch.rand(2))
  749. >>> v = (torch.zeros(2), torch.ones(2))
  750. >>> vhp(pow_adder_reducer, inputs, v)
  751. (tensor(4.8053),
  752. (tensor([0., 0.]),
  753. tensor([6., 6.])))
  754. """
  755. with torch.enable_grad():
  756. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "vhp")
  757. inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
  758. if v is not None:
  759. _, v = _as_tuple(v, "v", "vhp")
  760. v = _grad_preprocess(v, create_graph=create_graph, need_graph=False)
  761. _validate_v(v, inputs, is_inputs_tuple)
  762. else:
  763. if len(inputs) != 1 or inputs[0].nelement() != 1:
  764. raise RuntimeError("The vector v can only be None if the input to the user-provided function "
  765. "is a single Tensor with a single element.")
  766. outputs = func(*inputs)
  767. is_outputs_tuple, outputs = _as_tuple(outputs, "outputs of the user-provided function", "vhp")
  768. _check_requires_grad(outputs, "outputs", strict=strict)
  769. if is_outputs_tuple or not isinstance(outputs[0], torch.Tensor):
  770. raise RuntimeError("The function given to vhp should return a single Tensor")
  771. if outputs[0].nelement() != 1:
  772. raise RuntimeError("The Tensor returned by the function given to vhp should contain a single element")
  773. jac = _autograd_grad(outputs, inputs, create_graph=True)
  774. _check_requires_grad(jac, "jacobian", strict=strict)
  775. enable_grad = True if create_graph else torch.is_grad_enabled()
  776. with torch.set_grad_enabled(enable_grad):
  777. grad_res = _autograd_grad(jac, inputs, v, create_graph=create_graph)
  778. vhp = _fill_in_zeros(grad_res, inputs, strict, create_graph, "double_back")
  779. outputs = _grad_postprocess(outputs, create_graph)
  780. vhp = _grad_postprocess(vhp, create_graph)
  781. return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(vhp, is_inputs_tuple)
  782. def hvp(func, inputs, v=None, create_graph=False, strict=False):
  783. r"""Function that computes the dot product between the Hessian of a given scalar
  784. function and a vector ``v`` at the point given by the inputs.
  785. Args:
  786. func (function): a Python function that takes Tensor inputs and returns
  787. a Tensor with a single element.
  788. inputs (tuple of Tensors or Tensor): inputs to the function ``func``.
  789. v (tuple of Tensors or Tensor): The vector for which the Hessian vector
  790. product is computed. Must be the same size as the input of
  791. ``func``. This argument is optional when ``func``'s input contains
  792. a single element and (if it is not provided) will be set as a
  793. Tensor containing a single ``1``.
  794. create_graph (bool, optional): If ``True``, both the output and result will be
  795. computed in a differentiable way. Note that when ``strict`` is
  796. ``False``, the result can not require gradients or be disconnected
  797. from the inputs. Defaults to ``False``.
  798. strict (bool, optional): If ``True``, an error will be raised when we
  799. detect that there exists an input such that all the outputs are
  800. independent of it. If ``False``, we return a Tensor of zeros as the
  801. hvp for said inputs, which is the expected mathematical value.
  802. Defaults to ``False``.
  803. Returns:
  804. output (tuple): tuple with:
  805. func_output (tuple of Tensors or Tensor): output of ``func(inputs)``
  806. hvp (tuple of Tensors or Tensor): result of the dot product with
  807. the same shape as the inputs.
  808. Example:
  809. >>> def pow_reducer(x):
  810. ... return x.pow(3).sum()
  811. >>> inputs = torch.rand(2, 2)
  812. >>> v = torch.ones(2, 2)
  813. >>> hvp(pow_reducer, inputs, v)
  814. (tensor(0.1448),
  815. tensor([[2.0239, 1.6456],
  816. [2.4988, 1.4310]]))
  817. >>> hvp(pow_reducer, inputs, v, create_graph=True)
  818. (tensor(0.1448, grad_fn=<SumBackward0>),
  819. tensor([[2.0239, 1.6456],
  820. [2.4988, 1.4310]], grad_fn=<MulBackward0>))
  821. >>> def pow_adder_reducer(x, y):
  822. ... return (2 * x.pow(2) + 3 * y.pow(2)).sum()
  823. >>> inputs = (torch.rand(2), torch.rand(2))
  824. >>> v = (torch.zeros(2), torch.ones(2))
  825. >>> hvp(pow_adder_reducer, inputs, v)
  826. (tensor(2.3030),
  827. (tensor([0., 0.]),
  828. tensor([6., 6.])))
  829. Note:
  830. This function is significantly slower than `vhp` due to backward mode AD constraints.
  831. If your functions is twice continuously differentiable, then hvp = vhp.t(). So if you
  832. know that your function satisfies this condition, you should use vhp instead that is
  833. much faster with the current implementation.
  834. """
  835. with torch.enable_grad():
  836. is_inputs_tuple, inputs = _as_tuple(inputs, "inputs", "hvp")
  837. inputs = _grad_preprocess(inputs, create_graph=create_graph, need_graph=True)
  838. if v is not None:
  839. _, v = _as_tuple(v, "v", "hvp")
  840. v = _grad_preprocess(v, create_graph=create_graph, need_graph=False)
  841. _validate_v(v, inputs, is_inputs_tuple)
  842. else:
  843. if len(inputs) != 1 or inputs[0].nelement() != 1:
  844. raise RuntimeError("The vector v can only be None if the input to the user-provided function "
  845. "is a single Tensor with a single element.")
  846. outputs = func(*inputs)
  847. is_outputs_tuple, outputs = _as_tuple(outputs, "outputs of the user-provided function", "hvp")
  848. _check_requires_grad(outputs, "outputs", strict=strict)
  849. if is_outputs_tuple or not isinstance(outputs[0], torch.Tensor):
  850. raise RuntimeError("The function given to hvp should return a single Tensor")
  851. if outputs[0].nelement() != 1:
  852. raise RuntimeError("The Tensor returned by the function given to hvp should contain a single element")
  853. jac = _autograd_grad(outputs, inputs, create_graph=True)
  854. _check_requires_grad(jac, "jacobian", strict=strict)
  855. grad_jac = tuple(torch.zeros_like(inp, requires_grad=True) for inp in inputs)
  856. double_back = _autograd_grad(jac, inputs, grad_jac, create_graph=True)
  857. _check_requires_grad(jac, "hessian", strict=strict)
  858. enable_grad = True if create_graph else torch.is_grad_enabled()
  859. with torch.set_grad_enabled(enable_grad):
  860. grad_res = _autograd_grad(double_back, grad_jac, v, create_graph=create_graph)
  861. hvp = _fill_in_zeros(grad_res, inputs, strict, create_graph, "double_back_trick")
  862. outputs = _grad_postprocess(outputs, create_graph)
  863. hvp = _grad_postprocess(hvp, create_graph)
  864. return _tuple_postprocess(outputs, is_outputs_tuple), _tuple_postprocess(hvp, is_inputs_tuple)