make_functional.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. # mypy: allow-untyped-defs
  2. # Copyright (c) Facebook, Inc. and its affiliates.
  3. # All rights reserved.
  4. #
  5. # This source code is licensed under the BSD-style license found in the
  6. # LICENSE file in the root directory of this source tree.
  7. import copy
  8. from typing import (
  9. Any,
  10. Callable,
  11. Dict,
  12. Iterable,
  13. List,
  14. NoReturn,
  15. Sequence,
  16. Tuple,
  17. Type,
  18. Union,
  19. )
  20. import torch
  21. import torch.nn as nn
  22. from torch import Tensor
  23. from torch.nn.utils._named_member_accessor import NamedMemberAccessor
  24. # Utilities to make nn.Module "functional"
  25. # In particular the goal is to be able to provide a function that takes as input
  26. # the parameters and evaluate the nn.Module using fixed inputs.
  27. def raise_parameter_tying_error() -> NoReturn:
  28. raise RuntimeError(
  29. "make_functional(module): we don't yet support models that "
  30. "do parameter tying (also sometimes known as weight sharing). "
  31. "Please try to rewrite your model by replacing all instances of the "
  32. "tied parameter with another and/or comment your support in "
  33. "https://github.com/pytorch/functorch/issues/446"
  34. )
  35. def create_names_map(
  36. named_params: Union[Dict[str, Tensor], Iterable[Tuple[str, Tensor]]],
  37. tied_named_params: Union[Dict[str, Tensor], Iterable[Tuple[str, Tensor]]],
  38. ) -> Dict[str, List[str]]:
  39. """
  40. named_params is a dictionary of tensors: {'A': A, 'B': B}
  41. tied_named_params is another dictionary of tensors {'A': A, 'B': B, 'B_tied': B}
  42. with potentially tied (or 'duplicated') tensors
  43. This function creates a mapping from the names in named_params to the
  44. names in tied_named_params: {'A': ['A'], 'B': ['B', 'B_tied']}.
  45. """
  46. named_params = dict(named_params)
  47. tied_named_params = dict(tied_named_params)
  48. tensors_dict_keys = set(named_params.keys())
  49. tied_tensors_dict_keys = set(tied_named_params.keys())
  50. assert tensors_dict_keys.issubset(tied_tensors_dict_keys)
  51. tensor_to_mapping: Dict[Tensor, Tuple[str, List[str]]] = {}
  52. for key, tensor in named_params.items():
  53. tensor_to_mapping[tensor] = (key, [])
  54. for key, tensor in tied_named_params.items():
  55. assert tensor in tensor_to_mapping
  56. tensor_to_mapping[tensor][1].append(key)
  57. return dict(tensor_to_mapping.values())
  58. def _extract_members(
  59. mod: nn.Module,
  60. named_members: Callable[..., Iterable[Tuple[str, Tensor]]],
  61. subclass: Callable[[Tensor], Tensor],
  62. ) -> Tuple[Tuple[Tensor, ...], Tuple[str, ...], Dict[str, List[str]]]:
  63. all_named_members = tuple(named_members(remove_duplicate=False))
  64. unique_named_members = tuple(named_members(remove_duplicate=True))
  65. names_map = create_names_map(unique_named_members, all_named_members)
  66. # Remove all the members in the model
  67. memo = {}
  68. accessor = NamedMemberAccessor(mod)
  69. for name, p in all_named_members:
  70. if p not in memo:
  71. memo[p] = subclass(torch.empty_like(p, device="meta"))
  72. replacement = memo[p]
  73. accessor.set_tensor(name, replacement)
  74. if len(unique_named_members) == 0:
  75. names, params = (), ()
  76. else:
  77. names, params = zip(*unique_named_members) # type: ignore[assignment]
  78. return params, names, names_map
  79. def extract_weights(
  80. mod: nn.Module,
  81. ) -> Tuple[Tuple[Tensor, ...], Tuple[str, ...], Dict[str, List[str]]]:
  82. """
  83. This function removes all the Parameters from the model and
  84. return them as a tuple as well as their original attribute names.
  85. The weights must be re-loaded with `load_weights` before the model
  86. can be used again.
  87. Note that this function modifies the model in place and after this
  88. call, mod.parameters() will be empty.
  89. """
  90. return _extract_members(mod, mod.named_parameters, nn.Parameter)
  91. def extract_buffers(
  92. mod: nn.Module,
  93. ) -> Tuple[Tuple[Tensor, ...], Tuple[str, ...], Dict[str, List[str]]]:
  94. return _extract_members(mod, mod.named_buffers, lambda x: x)
  95. def load_weights(
  96. mod: nn.Module,
  97. names: Sequence[str],
  98. params: Sequence[Tensor],
  99. as_params: bool = False,
  100. ) -> None:
  101. """
  102. Reload a set of weights so that `mod` can be used again to perform a forward pass.
  103. Note that the `params` are regular Tensors (that can have history) and so are left
  104. as Tensors. This means that mod.parameters() will still be empty after this call.
  105. """
  106. accessor = NamedMemberAccessor(mod)
  107. if as_params:
  108. params = [nn.Parameter(p) for p in params]
  109. accessor.set_tensors(names, params)
  110. def _swap_state(
  111. mod: nn.Module, names_map: Dict[str, List[str]], elems: Iterable[Tensor]
  112. ) -> List[Tensor]:
  113. result: List[Tensor] = []
  114. accessor = NamedMemberAccessor(mod)
  115. for (_, attr_names), elem in zip(names_map.items(), elems):
  116. for i, attr_name in enumerate(attr_names):
  117. if i == 0:
  118. result.append(accessor.swap_tensor(attr_name, elem))
  119. else:
  120. accessor.set_tensor(attr_name, elem)
  121. return result
  122. def load_buffers(
  123. mod: nn.Module,
  124. names: Sequence[str],
  125. buffers: Sequence[Tensor],
  126. as_params: bool = False,
  127. ) -> None:
  128. accessor = NamedMemberAccessor(mod)
  129. accessor.set_tensors(names, buffers)
  130. def load_state(
  131. model: nn.Module,
  132. weights: Sequence[Tensor],
  133. weight_names: Sequence[str],
  134. buffers: Sequence[Tensor] = (),
  135. buffer_names: Sequence[str] = (),
  136. ) -> nn.Module:
  137. """load_state(model, weights, weight_names, buffers=(), buffer_names=()) -> model
  138. load_state takes `weights` and `buffers` and assigns them to the model.
  139. This is the inverse operation of `make_functional_deprecated_v1`.
  140. """
  141. assert len(weight_names) == len(weights)
  142. load_weights(model, weight_names, weights)
  143. if len(buffers) > 0:
  144. assert len(buffer_names) == len(buffers)
  145. load_buffers(model, buffer_names, buffers)
  146. return model
  147. def make_functional_deprecated_v1(model: nn.Module):
  148. """make_functional_deprecated_v1(model) -> weights, func, weight_names
  149. Given an nn.Module, make_functional_deprecated_v1 extracts the state (weights)
  150. and returns a functional version of the model, `func`. This makes
  151. it so that it is possible use transforms over the parameters of
  152. `model`.
  153. `func` can be invoked as follows:
  154. ```
  155. x = torch.randn(4, 3)
  156. model = nn.Linear(3, 3)
  157. weights, func, _ = make_functional_deprecated_v1(model)
  158. func(weights, (x,))
  159. ```
  160. And here is an example of applying the grad transform:
  161. ```
  162. x = torch.randn(4, 3)
  163. model = nn.Linear(3, 3)
  164. weights, _, func = make_functional_deprecated_v1(model)
  165. grad_weights = grad(func)(weights, (x,))
  166. ```
  167. To put the state back into a model, use `load_state`.
  168. """
  169. buffers = list(model.buffers())
  170. if len(buffers) > 0:
  171. raise RuntimeError(
  172. "make_functional_deprecated_v1(model): `model` has buffers. Please use "
  173. "make_functional_with_buffers_deprecated_v1(model) instead."
  174. )
  175. weights, descriptors, _ = extract_weights(model)
  176. def fun(weights, data):
  177. mutable_model = copy.deepcopy(model)
  178. load_weights(mutable_model, descriptors, weights)
  179. return mutable_model(*data)
  180. return weights, fun, descriptors
  181. def make_functional_with_buffers_deprecated_v1(model: nn.Module):
  182. """make_functional_with_buffers_deprecated_v1(model) -> weights, buffers, func, weight_names, buffer_names
  183. Given an nn.Module, make_functional_with_buffers_deprecated_v1 extracts the state (weights and buffers)
  184. and returns a functional version of the model, `func`.
  185. `func` can be invoked as follows:
  186. ```
  187. x = torch.randn(4, 3)
  188. model = nn.Linear(3, 3)
  189. weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
  190. func(weights, buffers, (x,))
  191. ```
  192. And here is an example of applying the grad transform:
  193. ```
  194. x = torch.randn(4, 3)
  195. model = nn.Linear(3, 3)
  196. weights, buffers, func, _, _ = make_functional_with_buffers_deprecated_v1(model)
  197. func(weights, buffers, (x,))
  198. grad_weights = grad(func)(weights, buffers, (x,))
  199. ```
  200. To put the state back into a model, use `load_state`.
  201. """
  202. weights, weight_descriptors, _ = extract_weights(model)
  203. buffers, buf_descriptors, _ = extract_buffers(model)
  204. def fun(weights, buffers, data):
  205. mutable_model = copy.deepcopy(model)
  206. load_weights(mutable_model, weight_descriptors, weights)
  207. load_buffers(mutable_model, buf_descriptors, buffers)
  208. return mutable_model(*data)
  209. return weights, buffers, fun, weight_descriptors, buf_descriptors
  210. class FunctionalModuleWithBuffers(nn.Module):
  211. """
  212. This is the callable object returned by :func:`make_functional_with_buffers`.
  213. """
  214. def __init__(
  215. self,
  216. stateless_model: nn.Module,
  217. param_names: Tuple[str, ...],
  218. buffer_names: Tuple[str, ...],
  219. param_names_map: Dict[str, List[str]],
  220. buffer_names_map: Dict[str, List[str]],
  221. ) -> None:
  222. super().__init__()
  223. self.stateless_model = stateless_model
  224. self.param_names = param_names
  225. self.buffer_names = buffer_names
  226. self.all_names_map = dict(param_names_map)
  227. self.all_names_map.update(buffer_names_map)
  228. @staticmethod
  229. def _create_from(
  230. model: nn.Module, disable_autograd_tracking: bool = False
  231. ) -> Tuple["FunctionalModuleWithBuffers", Tuple[Tensor, ...], Tuple[Tensor, ...]]:
  232. # TODO: We don't need to copy the model to create a stateless copy
  233. model_copy = copy.deepcopy(model)
  234. params, param_names, param_names_map = extract_weights(model_copy)
  235. buffers, buffer_names, buffer_names_map = extract_buffers(model_copy)
  236. if disable_autograd_tracking:
  237. for param in params:
  238. param.requires_grad_(False)
  239. return (
  240. FunctionalModuleWithBuffers(
  241. model_copy, param_names, buffer_names, param_names_map, buffer_names_map
  242. ),
  243. params,
  244. buffers,
  245. )
  246. def forward(
  247. self, params: Iterable[Tensor], buffers: Iterable[Tensor], *args, **kwargs
  248. ) -> Any:
  249. # Temporarily load the state back onto self.stateless_model
  250. old_state = _swap_state(
  251. self.stateless_model,
  252. self.all_names_map,
  253. tuple(params) + tuple(buffers),
  254. )
  255. try:
  256. return self.stateless_model(*args, **kwargs)
  257. finally:
  258. # Remove the loaded state on self.stateless_model
  259. _swap_state(self.stateless_model, self.all_names_map, old_state)
  260. class FunctionalModule(nn.Module):
  261. """
  262. This is the callable object returned by :func:`make_functional`.
  263. """
  264. def __init__(
  265. self,
  266. stateless_model: nn.Module,
  267. param_names: Tuple[str, ...],
  268. names_map: Dict[str, List[str]],
  269. ) -> None:
  270. super().__init__()
  271. self.stateless_model = stateless_model
  272. self.param_names = param_names
  273. self.names_map = names_map
  274. @staticmethod
  275. def _create_from(
  276. model: nn.Module, disable_autograd_tracking: bool = False
  277. ) -> Tuple["FunctionalModule", Tuple[Tensor, ...]]:
  278. # TODO: We don't need to copy the model to create a stateless copy
  279. model_copy = copy.deepcopy(model)
  280. params, param_names, names_map = extract_weights(model_copy)
  281. if disable_autograd_tracking:
  282. for param in params:
  283. param.requires_grad_(False)
  284. return FunctionalModule(model_copy, param_names, names_map), params
  285. def forward(self, params: Iterable[Tensor], *args, **kwargs) -> Any:
  286. # Temporarily load the state back onto self.stateless_model
  287. old_state = _swap_state(self.stateless_model, self.names_map, params)
  288. try:
  289. return self.stateless_model(*args, **kwargs)
  290. finally:
  291. # Remove the loaded state on self.stateless_model
  292. _swap_state(self.stateless_model, self.names_map, old_state)
  293. def make_functional(
  294. model: nn.Module, disable_autograd_tracking: bool = False
  295. ) -> Tuple[FunctionalModule, Tuple[Tensor, ...]]:
  296. """make_functional(model, disable_autograd_tracking=False) -> func, params
  297. Given a ``torch.nn.Module``, :func:`make_functional` extracts the state
  298. (params) and returns a functional version of the model, ``func``. This
  299. makes it so that it is possible use transforms over the parameters of
  300. ``model``.
  301. ``func`` can be invoked as follows:
  302. .. code-block:: python
  303. import torch
  304. import torch.nn as nn
  305. from functorch import make_functional
  306. x = torch.randn(4, 3)
  307. model = nn.Linear(3, 3)
  308. func, params = make_functional(model)
  309. func(params, x)
  310. And here is an example of applying the grad transform over the parameters
  311. of a model.
  312. .. code-block:: python
  313. import torch
  314. import torch.nn as nn
  315. from functorch import make_functional, grad
  316. x = torch.randn(4, 3)
  317. t = torch.randn(4, 3)
  318. model = nn.Linear(3, 3)
  319. func, params = make_functional(model)
  320. def compute_loss(params, x, t):
  321. y = func(params, x)
  322. return nn.functional.mse_loss(y, t)
  323. grad_weights = grad(compute_loss)(params, x, t)
  324. If the model has any buffers, please use :func:`make_functional_with_buffers` instead.
  325. Args:
  326. model (torch.nn.Module): Input model.
  327. disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
  328. The returned params are unrelated to the set of params from the original model. If False (default),
  329. the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
  330. PyTorch autograd), matching the requires_grad-ness of the params from the original model.
  331. Otherwise, the returned params will have ``requires_grad=False``. Default, False.
  332. If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
  333. ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
  334. Otherwise, if you're only planning on using functorch's gradient transforms,
  335. then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
  336. history with PyTorch autograd.
  337. """
  338. buffers = list(model.buffers())
  339. if len(buffers) > 0:
  340. raise RuntimeError(
  341. "make_functional(model): `model` has buffers. Please use "
  342. "make_functional_with_buffers(model) instead."
  343. )
  344. return FunctionalModule._create_from(
  345. model, disable_autograd_tracking=disable_autograd_tracking
  346. )
  347. def make_functional_with_buffers(
  348. model: nn.Module, disable_autograd_tracking: bool = False
  349. ) -> Tuple[FunctionalModuleWithBuffers, Tuple[Tensor, ...], Tuple[Tensor, ...]]:
  350. """make_functional_with_buffers(model, disable_autograd_tracking=False) -> func, params, buffers
  351. Given a ``torch.nn.Module``, make_functional_with_buffers extracts the
  352. state (params and buffers) and returns a functional version of the model
  353. ``func`` that can be invoked like a function.
  354. ``func`` can be invoked as follows:
  355. .. code-block:: python
  356. import torch
  357. import torch.nn as nn
  358. from functorch import make_functional_with_buffers
  359. x = torch.randn(4, 3)
  360. model = nn.Linear(3, 3)
  361. func, params, buffers = make_functional_with_buffers(model)
  362. func(params, buffers, x)
  363. And here is an example of applying the grad transform over the parameters
  364. of a model:
  365. .. code-block:: python
  366. import torch
  367. import torch.nn as nn
  368. from functorch import make_functional_with_buffers, grad
  369. x = torch.randn(4, 3)
  370. t = torch.randn(4, 3)
  371. model = nn.Linear(3, 3)
  372. func, params, buffers = make_functional_with_buffers(model)
  373. def compute_loss(params, buffers, x, t):
  374. y = func(params, buffers, x)
  375. return nn.functional.mse_loss(y, t)
  376. grad_weights = grad(compute_loss)(params, buffers, x, t)
  377. Args:
  378. model (torch.nn.Module): Input model.
  379. disable_autograd_tracking (bool): Flag to disable gradients tracking for output parameters.
  380. The returned params are unrelated to the set of params from the original model. If False (default),
  381. the params will have ``requires_grad=True`` on them (aka they will be trackable with regular
  382. PyTorch autograd), matching the requires_grad-ness of the params from the original model.
  383. Otherwise, the returned params will have ``requires_grad=False``. Default, False.
  384. If you plan on using regular PyTorch autograd (e.g., if you want to call ``.backward()`` or
  385. ``torch.autograd.grad()``, then set ``disable_autograd_tracking=False``.
  386. Otherwise, if you're only planning on using functorch's gradient transforms,
  387. then please set ``disable_autograd_tracking=True`` to avoid unnecessarily tracking
  388. history with PyTorch autograd.
  389. """
  390. return FunctionalModuleWithBuffers._create_from(
  391. model, disable_autograd_tracking=disable_autograd_tracking
  392. )
  393. def transpose_stack(
  394. tuple_of_tuple_of_tensors: Tuple[Tuple[Tensor, ...], ...]
  395. ) -> Tuple[Tensor, ...]:
  396. tuple_of_tuple_of_tensors = tuple(zip(*tuple_of_tuple_of_tensors))
  397. results = tuple(
  398. torch.stack(shards).detach() for shards in tuple_of_tuple_of_tensors
  399. )
  400. return results
  401. def combine_state_for_ensemble(
  402. models: Sequence[nn.Module],
  403. ) -> Tuple[FunctionalModuleWithBuffers, Tuple[Tensor, ...], Tuple[Tensor, ...]]:
  404. """combine_state_for_ensemble(models) -> func, params, buffers
  405. Prepares a list of torch.nn.Modules for ensembling with :func:`vmap`.
  406. Given a list of ``M`` ``nn.Modules`` of the same class, stacks all of their
  407. parameters and buffers together to make ``params`` and ``buffers``.
  408. Each parameter and buffer in the result will have an additional dimension
  409. of size ``M``.
  410. :func:`combine_state_for_ensemble` also returns ``func``, a functional
  411. version of one of the models in :attr:`models`. One cannot directly run
  412. ``func(params, buffers, *args, **kwargs)`` directly, you probably want to
  413. use ``vmap(func, ...)(params, buffers, *args, **kwargs)``
  414. Here's an example of how to ensemble over a very simple model:
  415. .. code-block:: python
  416. num_models = 5
  417. batch_size = 64
  418. in_features, out_features = 3, 3
  419. models = [torch.nn.Linear(in_features, out_features) for i in range(num_models)]
  420. data = torch.randn(batch_size, 3)
  421. fmodel, params, buffers = combine_state_for_ensemble(models)
  422. output = vmap(fmodel, (0, 0, None))(params, buffers, data)
  423. assert output.shape == (num_models, batch_size, out_features)
  424. .. warning::
  425. All of the modules being stacked together must be the same (except for
  426. the values of their parameters/buffers). For example, they should be in the
  427. same mode (training vs eval).
  428. This API is subject to change -- we're investigating better ways to
  429. create ensembles and would love your feedback how to improve this.
  430. """
  431. if len(models) == 0:
  432. raise RuntimeError(
  433. "combine_state_for_ensemble: Expected at least one model, got 0."
  434. )
  435. if not (all(m.training for m in models) or all(not m.training for m in models)):
  436. raise RuntimeError(
  437. "combine_state_for_ensemble: Expected all models to "
  438. "have the same training/eval mode."
  439. )
  440. model0_typ = type(models[0])
  441. if not all(type(m) == model0_typ for m in models):
  442. raise RuntimeError(
  443. "combine_state_for_ensemble: Expected all models to be of the same class."
  444. )
  445. funcs, params, buffers = zip(
  446. *[make_functional_with_buffers(model) for model in models]
  447. )
  448. params = transpose_stack(params)
  449. buffers = transpose_stack(buffers)
  450. return funcs[0], params, buffers
  451. def functional_init(
  452. model_class: Type[nn.Module],
  453. ensemble_shape: Union[Tuple[()], Tuple[int]] = (),
  454. device: torch.types.Device = "cpu",
  455. ):
  456. def wrapped(*args, **kwargs):
  457. if len(ensemble_shape) >= 2:
  458. raise ValueError("NYI: ensemble_shape with more than 1 element")
  459. if len(ensemble_shape) == 0:
  460. model = model_class(*args, **kwargs).to(device)
  461. return make_functional_deprecated_v1(model)
  462. num_models = ensemble_shape[0] # type: ignore[misc]
  463. if num_models <= 0:
  464. raise ValueError(f"num_models {num_models} should be > 0")
  465. # NB: Not very efficient, more of a POC
  466. models = tuple(
  467. model_class(*args, **kwargs).to(device) for _ in range(num_models)
  468. )
  469. _, fn, names = make_functional_deprecated_v1(model_class(*args, **kwargs))
  470. weights = tuple(make_functional_deprecated_v1(model)[0] for model in models)
  471. weights = tuple(zip(*weights))
  472. weights = tuple(torch.stack(shards).detach() for shards in weights)
  473. return weights, fn, names
  474. return wrapped
  475. def functional_init_with_buffers(
  476. model_class: Type[nn.Module],
  477. ensemble_shape: Union[Tuple[()], Tuple[int]] = (),
  478. device: torch.types.Device = "cpu",
  479. ):
  480. def wrapped(*args, **kwargs):
  481. if len(ensemble_shape) >= 2:
  482. raise ValueError("NYI: ensemble_shape with more than 1 element")
  483. if len(ensemble_shape) == 0:
  484. model = model_class(*args, **kwargs).to(device)
  485. return make_functional_deprecated_v1(model)
  486. num_models = ensemble_shape[0] # type: ignore[misc]
  487. if num_models <= 0:
  488. raise ValueError(f"num_models {num_models} should be > 0")
  489. # NB: Not very efficient, more of a POC
  490. models = tuple(
  491. model_class(*args, **kwargs).to(device) for _ in range(num_models)
  492. )
  493. (
  494. _,
  495. _,
  496. fn,
  497. weight_names,
  498. buffer_names,
  499. ) = make_functional_with_buffers_deprecated_v1(model_class(*args, **kwargs))
  500. weights, buffers = zip(
  501. *tuple(
  502. make_functional_with_buffers_deprecated_v1(model)[:2]
  503. for model in models
  504. )
  505. )
  506. weights = tuple(zip(*weights))
  507. weights = tuple(torch.stack(shards).detach() for shards in weights)
  508. buffers = tuple(zip(*buffers))
  509. buffers = tuple(torch.stack(shards).detach() for shards in buffers)
  510. return weights, buffers, fn, weight_names, buffer_names
  511. return wrapped