functional_call.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. from collections import Counter
  2. from typing import Any, Dict, List, Sequence, Tuple, Union
  3. import torch
  4. import torch.nn as nn
  5. from torch import Tensor
  6. from torch._functorch.utils import exposed_in
  7. @exposed_in("torch.func")
  8. def functional_call(
  9. module: "torch.nn.Module",
  10. parameter_and_buffer_dicts: Union[Dict[str, Tensor], Sequence[Dict[str, Tensor]]],
  11. args: Union[Any, Tuple],
  12. kwargs: Dict[str, Any] = None,
  13. *,
  14. tie_weights: bool = True,
  15. strict: bool = False,
  16. ):
  17. r"""Performs a functional call on the module by replacing the module parameters
  18. and buffers with the provided ones.
  19. .. note:: If the module has active parametrizations, passing a value in the
  20. :attr:`parameters_and_buffers` argument with the name set to the regular parameter
  21. name will completely disable the parametrization.
  22. If you want to apply the parametrization function to the value passed
  23. please set the key as ``{submodule_name}.parametrizations.{parameter_name}.original``.
  24. .. note:: If the module performs in-place operations on parameters/buffers, these will be reflected
  25. in the ``parameters_and_buffers`` input.
  26. Example::
  27. >>> a = {'foo': torch.zeros(())}
  28. >>> # xdoctest: +SKIP
  29. >>> mod = Foo() # does self.foo = self.foo + 1
  30. >>> print(mod.foo) # tensor(0.)
  31. >>> functional_call(mod, a, torch.ones(()))
  32. >>> print(mod.foo) # tensor(0.)
  33. >>> print(a['foo']) # tensor(1.)
  34. .. note:: If the module has tied weights, whether or not functional_call respects the tying is determined by the
  35. tie_weights flag.
  36. Example::
  37. >>> a = {'foo': torch.zeros(())}
  38. >>> # xdoctest: +SKIP
  39. >>> mod = Foo() # has both self.foo and self.foo_tied which are tied. Returns x + self.foo + self.foo_tied
  40. >>> print(mod.foo) # tensor(1.)
  41. >>> mod(torch.zeros(())) # tensor(2.)
  42. >>> functional_call(mod, a, torch.zeros(())) # tensor(0.) since it will change self.foo_tied too
  43. >>> functional_call(mod, a, torch.zeros(()), tie_weights=False) # tensor(1.)--self.foo_tied is not updated
  44. >>> new_a = {'foo', torch.zeros(()), 'foo_tied': torch.zeros(())}
  45. >>> functional_call(mod, new_a, torch.zeros()) # tensor(0.)
  46. An example of passing mutliple dictionaries
  47. .. code-block:: python
  48. a = ({'weight': torch.ones(1, 1)}, {'buffer': torch.zeros(1)}) # two separate dictionaries
  49. mod = nn.Bar(1, 1) # return self.weight @ x + self.buffer
  50. print(mod.weight) # tensor(...)
  51. print(mod.buffer) # tensor(...)
  52. x = torch.randn((1, 1))
  53. print(x)
  54. functional_call(mod, a, x) # same as x
  55. print(mod.weight) # same as before functional_call
  56. And here is an example of applying the grad transform over the parameters
  57. of a model.
  58. .. code-block:: python
  59. import torch
  60. import torch.nn as nn
  61. from torch.func import functional_call, grad
  62. x = torch.randn(4, 3)
  63. t = torch.randn(4, 3)
  64. model = nn.Linear(3, 3)
  65. def compute_loss(params, x, t):
  66. y = functional_call(model, params, x)
  67. return nn.functional.mse_loss(y, t)
  68. grad_weights = grad(compute_loss)(dict(model.named_parameters()), x, t)
  69. .. note:: If the user does not need grad tracking outside of grad transforms, they can detach all of the
  70. parameters for better performance and memory usage
  71. Example::
  72. >>> detached_params = {k: v.detach() for k, v in model.named_parameters()}
  73. >>> grad_weights = grad(compute_loss)(detached_params, x, t)
  74. >>> grad_weights.grad_fn # None--it's not tracking gradients outside of grad
  75. This means that the user cannot call ``grad_weight.backward()``. However, if they don't need autograd tracking
  76. outside of the transforms, this will result in less memory usage and faster speeds.
  77. Args:
  78. module (torch.nn.Module): the module to call
  79. parameters_and_buffers (Dict[str, Tensor] or tuple of Dict[str, Tensor]): the parameters that will be used in
  80. the module call. If given a tuple of dictionaries, they must have distinct keys so that all dictionaries can
  81. be used together
  82. args (Any or tuple): arguments to be passed to the module call. If not a tuple, considered a single argument.
  83. kwargs (dict): keyword arguments to be passed to the module call
  84. tie_weights (bool, optional): If True, then parameters and buffers tied in the original model will be treated as
  85. tied in the reparamaterized version. Therefore, if True and different values are passed for the tied
  86. paramaters and buffers, it will error. If False, it will not respect the originally tied parameters and
  87. buffers unless the values passed for both weights are the same. Default: True.
  88. strict (bool, optional): If True, then the parameters and buffers passed in must match the parameters and
  89. buffers in the original module. Therefore, if True and there are any missing or unexpected keys, it will
  90. error. Default: False.
  91. Returns:
  92. Any: the result of calling ``module``.
  93. """
  94. if isinstance(parameter_and_buffer_dicts, dict):
  95. parameters_and_buffers = parameter_and_buffer_dicts
  96. elif isinstance(parameter_and_buffer_dicts, Sequence):
  97. if not all(isinstance(d, dict) for d in parameter_and_buffer_dicts):
  98. raise ValueError(
  99. "Expected all elements of parameter_and_buffer_dicts to be dictionaries"
  100. )
  101. all_keys = [k for d in parameter_and_buffer_dicts for k in d.keys()]
  102. repeated_keys = [key for key, n in Counter(all_keys).items() if n > 1]
  103. if len(repeated_keys) > 0:
  104. raise ValueError(
  105. f"{repeated_keys} appeared in multiple dictionaries; behavior of functional call is ambiguous"
  106. )
  107. parameters_and_buffers = {
  108. k: v for d in parameter_and_buffer_dicts for k, v in d.items()
  109. }
  110. else:
  111. raise ValueError(
  112. f"Expected parameter_and_buffer_dicts to be a dict, or a list/tuple of dicts, "
  113. f"but got {type(parameter_and_buffer_dicts)}"
  114. )
  115. return nn.utils.stateless._functional_call(
  116. module,
  117. parameters_and_buffers,
  118. args,
  119. kwargs,
  120. tie_weights=tie_weights,
  121. strict=strict,
  122. )
  123. @exposed_in("torch.func")
  124. def stack_module_state(
  125. models: List[nn.Module],
  126. ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
  127. """stack_module_state(models) -> params, buffers
  128. Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
  129. Given a list of ``M`` ``nn.Modules`` of the same class, returns two dictionaries
  130. that stack all of their parameters and buffers together, indexed by name.
  131. The stacked parameters are optimizable (i.e. they are new leaf nodes in the
  132. autograd history that are unrelated to the original parameters and can be
  133. passed directly to an optimizer).
  134. Here's an example of how to ensemble over a very simple model:
  135. .. code-block:: python
  136. num_models = 5
  137. batch_size = 64
  138. in_features, out_features = 3, 3
  139. models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
  140. data = torch.randn(batch_size, 3)
  141. def wrapper(params, buffers, data):
  142. return torch.func.functional_call(model[0], (params, buffers), data)
  143. params, buffers = stack_module_state(models)
  144. output = vmap(wrapper, (0, 0, None))(params, buffers, data)
  145. assert output.shape == (num_models, batch_size, out_features)
  146. When there's submodules, this follows state dict naming conventions
  147. .. code-block:: python
  148. import torch.nn as nn
  149. class Foo(nn.Module):
  150. def __init__(self, in_features, out_features):
  151. super().__init__()
  152. hidden = 4
  153. self.l1 = nn.Linear(in_features, hidden)
  154. self.l2 = nn.Linear(hidden, out_features)
  155. def forward(self, x):
  156. return self.l2(self.l1(x))
  157. num_models = 5
  158. in_features, out_features = 3, 3
  159. models = [Foo(in_features, out_features) for i in range(num_models)]
  160. params, buffers = stack_module_state(models)
  161. print(list(params.keys())) # "l1.weight", "l1.bias", "l2.weight", "l2.bias"
  162. .. warning::
  163. All of the modules being stacked together must be the same (except for
  164. the values of their parameters/buffers). For example, they should be in the
  165. same mode (training vs eval).
  166. """
  167. if len(models) == 0:
  168. raise RuntimeError("stack_module_state: Expected at least one model, got 0.")
  169. if not (all(m.training for m in models) or all(not m.training for m in models)):
  170. raise RuntimeError(
  171. "stack_module_state: Expected all models to have the same training/eval mode."
  172. )
  173. model0_typ = type(models[0])
  174. if not all(type(m) == model0_typ for m in models):
  175. raise RuntimeError(
  176. "stack_module_state: Expected all models to be of the same class."
  177. )
  178. all_params = [dict(model.named_parameters()) for model in models]
  179. params = {
  180. k: construct_stacked_leaf(tuple(params[k] for params in all_params), k)
  181. for k in all_params[0]
  182. }
  183. all_buffers = [dict(model.named_buffers()) for model in models]
  184. buffers = {
  185. k: construct_stacked_leaf(tuple(buffers[k] for buffers in all_buffers), k)
  186. for k in all_buffers[0]
  187. }
  188. return params, buffers
  189. def construct_stacked_leaf(
  190. tensors: Union[Tuple[Tensor, ...], List[Tensor]], name: str
  191. ) -> Tensor:
  192. all_requires_grad = all(t.requires_grad for t in tensors)
  193. none_requires_grad = all(not t.requires_grad for t in tensors)
  194. if not all_requires_grad and not none_requires_grad:
  195. raise RuntimeError(
  196. f"Expected {name} from each model to have the same .requires_grad"
  197. )
  198. result = torch.stack(tensors)
  199. if all_requires_grad:
  200. result = result.detach().requires_grad_()
  201. return result