functional.py 52 KB

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