functional.py 51 KB

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