parametrize.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. import torch
  2. from torch.nn.modules.container import ModuleList, ModuleDict, Module
  3. from torch.nn.parameter import Parameter
  4. from torch import Tensor
  5. import collections
  6. import copyreg
  7. from copy import deepcopy
  8. from contextlib import contextmanager
  9. from typing import Union, Optional, Dict, Tuple, Sequence
  10. __all__ = ['cached', 'ParametrizationList', 'register_parametrization', 'is_parametrized', 'remove_parametrizations',
  11. 'type_before_parametrizations', 'transfer_parametrizations_and_params']
  12. _cache_enabled = 0
  13. _cache: Dict[Tuple[int, str], Optional[Tensor]] = {}
  14. @contextmanager
  15. def cached():
  16. r"""Context manager that enables the caching system within parametrizations
  17. registered with :func:`register_parametrization`.
  18. The value of the parametrized objects is computed and cached the first time
  19. they are required when this context manager is active. The cached values are
  20. discarded when leaving the context manager.
  21. This is useful when using a parametrized parameter more than once in the forward pass.
  22. An example of this is when parametrizing the recurrent kernel of an RNN or when
  23. sharing weights.
  24. The simplest way to activate the cache is by wrapping the forward pass of the neural network
  25. .. code-block:: python
  26. import torch.nn.utils.parametrize as P
  27. ...
  28. with P.cached():
  29. output = model(inputs)
  30. in training and evaluation. One may also wrap the parts of the modules that use
  31. several times the parametrized tensors. For example, the loop of an RNN with a
  32. parametrized recurrent kernel:
  33. .. code-block:: python
  34. with P.cached():
  35. for x in xs:
  36. out_rnn = self.rnn_cell(x, out_rnn)
  37. """
  38. global _cache
  39. global _cache_enabled
  40. _cache_enabled += 1
  41. try:
  42. yield
  43. finally:
  44. _cache_enabled -= 1
  45. if not _cache_enabled:
  46. _cache = {}
  47. def _register_parameter_or_buffer(module, name, X):
  48. if isinstance(X, Parameter):
  49. module.register_parameter(name, X)
  50. else:
  51. module.register_buffer(name, X)
  52. class ParametrizationList(ModuleList):
  53. r"""A sequential container that holds and manages the ``original`` or ``original0``, ``original1``, ...
  54. parameters or buffers of a parametrized :class:`torch.nn.Module`.
  55. It is the type of ``module.parametrizations[tensor_name]`` when ``module[tensor_name]``
  56. has been parametrized with :func:`register_parametrization`.
  57. If the first registered parametrization has a ``right_inverse`` that returns one tensor or
  58. does not have a ``right_inverse`` (in which case we assume that ``right_inverse`` is the identity),
  59. it will hold the tensor under the name ``original``.
  60. If it has a ``right_inverse`` that returns more than one tensor, these will be registered as
  61. ``original0``, ``original1``, ...
  62. .. warning::
  63. This class is used internally by :func:`register_parametrization`. It is documented
  64. here for completeness. It shall not be instantiated by the user.
  65. Args:
  66. modules (sequence): sequence of modules representing the parametrizations
  67. original (Parameter or Tensor): parameter or buffer that is parametrized
  68. unsafe (bool): a boolean flag that denotes whether the parametrization
  69. may change the dtype and shape of the tensor. Default: `False`
  70. Warning: the parametrization is not checked for consistency upon registration.
  71. Enable this flag at your own risk.
  72. """
  73. original: Tensor
  74. unsafe: bool
  75. def __init__(
  76. self, modules: Sequence[Module], original: Union[Tensor, Parameter], unsafe: bool = False
  77. ) -> None:
  78. # We require this because we need to treat differently the first parametrization
  79. # This should never throw, unless this class is used from the outside
  80. if len(modules) == 0:
  81. raise ValueError("ParametrizationList requires one or more modules.")
  82. super().__init__(modules)
  83. self.unsafe = unsafe
  84. # In plain words:
  85. # module.weight must keep its dtype and shape.
  86. # Furthermore, if there is no right_inverse or the right_inverse returns a tensor,
  87. # this should be of the same dtype as the original tensor
  88. #
  89. # We check that the following invariants hold:
  90. # X = module.weight
  91. # Y = param.right_inverse(X)
  92. # assert isinstance(Y, Tensor) or
  93. # (isinstance(Y, collections.abc.Sequence) and all(isinstance(t, Tensor) for t in Y))
  94. # Z = param(Y) if isisntance(Y, Tensor) else param(*Y)
  95. # # Consistency checks
  96. # assert X.dtype == Z.dtype and X.shape == Z.shape
  97. # # If it has one input, this allows to be able to use set_ to be able to
  98. # # move data to/from the original tensor without changing its id (which is what the
  99. # # optimizer uses to track parameters)
  100. # if isinstance(Y, Tensor)
  101. # assert X.dtype == Y.dtype
  102. # Below we use original = X, new = Y
  103. original_shape = original.shape
  104. original_dtype = original.dtype
  105. # Compute new
  106. with torch.no_grad():
  107. new = original
  108. for module in reversed(self): # type: ignore[call-overload]
  109. if hasattr(module, "right_inverse"):
  110. try:
  111. new = module.right_inverse(new)
  112. except NotImplementedError:
  113. pass
  114. # else, or if it throws, we assume that right_inverse is the identity
  115. if not isinstance(new, Tensor) and not isinstance(new, collections.abc.Sequence):
  116. raise ValueError("'right_inverse' must return a Tensor or a Sequence of tensors (list, tuple...). "
  117. f"Got {type(new).__name__}")
  118. # Set the number of original tensors
  119. self.is_tensor = isinstance(new, Tensor)
  120. self.ntensors = 1 if self.is_tensor else len(new)
  121. # Register the tensor(s)
  122. if self.is_tensor:
  123. if original.dtype != new.dtype:
  124. raise ValueError(
  125. "When `right_inverse` outputs one tensor, it may not change the dtype.\n"
  126. f"original.dtype: {original.dtype}\n"
  127. f"right_inverse(original).dtype: {new.dtype}"
  128. )
  129. # Set the original to original so that the user does not need to re-register the parameter
  130. # manually in the optimiser
  131. with torch.no_grad():
  132. original.set_(new) # type: ignore[call-overload]
  133. _register_parameter_or_buffer(self, "original", original)
  134. else:
  135. for i, originali in enumerate(new):
  136. if not isinstance(originali, Tensor):
  137. raise ValueError("'right_inverse' must return a Tensor or a Sequence of tensors "
  138. "(list, tuple...). "
  139. f"Got element {i} of the sequence with type {type(originali).__name__}.")
  140. # If the original tensor was a Parameter that required grad, we expect the user to
  141. # add the new parameters to the optimizer after registering the parametrization
  142. # (this is documented)
  143. if isinstance(original, Parameter):
  144. originali = Parameter(originali)
  145. originali.requires_grad_(original.requires_grad)
  146. _register_parameter_or_buffer(self, f"original{i}", originali)
  147. if not self.unsafe:
  148. # Consistency checks:
  149. # Since f : A -> B, right_inverse : B -> A, Z and original should live in B
  150. # Z = forward(right_inverse(original))
  151. Z = self()
  152. if not isinstance(Z, Tensor):
  153. raise ValueError(
  154. f"A parametrization must return a tensor. Got {type(Z).__name__}."
  155. )
  156. if Z.dtype != original_dtype:
  157. raise ValueError(
  158. "Registering a parametrization may not change the dtype of the tensor, unless `unsafe` flag is enabled.\n"
  159. f"unparametrized dtype: {original_dtype}\n"
  160. f"parametrized dtype: {Z.dtype}"
  161. )
  162. if Z.shape != original_shape:
  163. raise ValueError(
  164. "Registering a parametrization may not change the shape of the tensor, unless `unsafe` flag is enabled.\n"
  165. f"unparametrized shape: {original_shape}\n"
  166. f"parametrized shape: {Z.shape}"
  167. )
  168. def right_inverse(self, value: Tensor) -> None:
  169. r"""Calls the methods ``right_inverse`` (see :func:`register_parametrization`)
  170. of the parametrizations in the inverse order they were registered in.
  171. Then, it stores the result in ``self.original`` if ``right_inverse`` outputs one tensor
  172. or in ``self.original0``, ``self.original1``, ... if it outputs several.
  173. Args:
  174. value (Tensor): Value to which initialize the module
  175. """
  176. # All the exceptions in this function should almost never throw.
  177. # They could throw if, for example, right_inverse function returns a different
  178. # dtype when given a different input, which should most likely be caused by a
  179. # bug in the user's code
  180. with torch.no_grad():
  181. # See https://github.com/pytorch/pytorch/issues/53103
  182. for module in reversed(self): # type: ignore[call-overload]
  183. if hasattr(module, "right_inverse"):
  184. value = module.right_inverse(value)
  185. else:
  186. raise RuntimeError(f"parametrization {type(module).__name__} does not implement "
  187. "right_inverse.")
  188. if self.is_tensor:
  189. # These exceptions should only throw when a right_inverse function does not
  190. # return the same dtype for every input, which should most likely be caused by a bug
  191. if not isinstance(value, Tensor):
  192. raise ValueError(
  193. f"`right_inverse` should return a tensor. Got {type(value).__name__}"
  194. )
  195. if value.dtype != self.original.dtype:
  196. raise ValueError(
  197. f"The tensor returned by `right_inverse` has dtype {value.dtype} "
  198. f"while `original` has dtype {self.original.dtype}"
  199. )
  200. # We know that the result is going to have the same dtype
  201. self.original.set_(value) # type: ignore[call-overload]
  202. else:
  203. if not isinstance(value, collections.abc.Sequence):
  204. raise ValueError(
  205. "'right_inverse' must return a sequence of tensors. "
  206. f"Got {type(value).__name__}."
  207. )
  208. if len(value) != self.ntensors:
  209. raise ValueError(
  210. "'right_inverse' must return a sequence of tensors of length "
  211. f"{self.ntensors}. Got a sequence of length {len(value)}."
  212. )
  213. for i, tensor in enumerate(value):
  214. original_i = getattr(self, f"original{i}")
  215. if not isinstance(tensor, Tensor):
  216. raise ValueError(
  217. f"`right_inverse` must return a sequence of tensors. "
  218. f"Got element {i} of type {type(tensor).__name__}"
  219. )
  220. if original_i.dtype != tensor.dtype:
  221. raise ValueError(
  222. f"Tensor {i} returned by `right_inverse` has dtype {tensor.dtype} "
  223. f"while `original{i}` has dtype {original_i.dtype}"
  224. )
  225. original_i.set_(tensor)
  226. def forward(self) -> Tensor:
  227. if torch.jit.is_scripting():
  228. raise RuntimeError('Parametrization is not working with scripting.')
  229. # Unpack the originals for the first parametrization
  230. if self.is_tensor:
  231. x = self[0](self.original)
  232. else:
  233. originals = (getattr(self, f"original{i}") for i in range(self.ntensors))
  234. x = self[0](*originals)
  235. # It's not possible to call self[1:] here, so we have to be a bit more cryptic
  236. # Also we want to skip all non-integer keys
  237. curr_idx = 1
  238. while hasattr(self, str(curr_idx)):
  239. x = self[curr_idx](x)
  240. curr_idx += 1
  241. return x
  242. def _inject_new_class(module: Module) -> None:
  243. r"""Sets up a module to be parametrized.
  244. This works by substituting the class of the module by a class
  245. that extends it to be able to inject a property
  246. Args:
  247. module (nn.Module): module into which to inject the property
  248. """
  249. cls = module.__class__
  250. def default_deepcopy(self, memo):
  251. # Just emulate a standard deepcopy procedure when __deepcopy__ doesn't exist in the current class.
  252. obj = memo.get(id(self), None)
  253. if obj is not None:
  254. return obj
  255. replica = self.__new__(self.__class__)
  256. memo[id(self)] = replica
  257. replica.__dict__ = deepcopy(self.__dict__, memo)
  258. # Also save all slots if they exist.
  259. slots_to_save = copyreg._slotnames(self.__class__) # type: ignore[attr-defined]
  260. for slot in slots_to_save:
  261. if hasattr(self, slot):
  262. setattr(replica, slot, deepcopy(getattr(self, slot), memo))
  263. return replica
  264. def getstate(self):
  265. raise RuntimeError(
  266. "Serialization of parametrized modules is only "
  267. "supported through state_dict(). See:\n"
  268. "https://pytorch.org/tutorials/beginner/saving_loading_models.html"
  269. "#saving-loading-a-general-checkpoint-for-inference-and-or-resuming-training"
  270. )
  271. dct = {"__getstate__": getstate}
  272. # We don't allow serialization of parametrized modules but should still allow deepcopying.
  273. # Default 'deepcopy' function invokes __deepcopy__ method instead of __getstate__ when it exists.
  274. if not hasattr(cls, "__deepcopy__"):
  275. dct["__deepcopy__"] = default_deepcopy # type: ignore[assignment]
  276. param_cls = type(
  277. f"Parametrized{cls.__name__}",
  278. (cls,),
  279. dct,
  280. )
  281. module.__class__ = param_cls
  282. def _inject_property(module: Module, tensor_name: str) -> None:
  283. r"""Injects a property into module[tensor_name].
  284. It assumes that the class in the module has already been modified from its
  285. original one using _inject_new_class and that the tensor under :attr:`tensor_name`
  286. has already been moved out
  287. Args:
  288. module (nn.Module): module into which to inject the property
  289. tensor_name (str): name of the name of the property to create
  290. """
  291. # We check the precondition.
  292. # This should never fire if register_parametrization is correctly implemented
  293. assert not hasattr(module, tensor_name)
  294. @torch.jit.unused
  295. def get_cached_parametrization(parametrization) -> Tensor:
  296. global _cache
  297. key = (id(module), tensor_name)
  298. tensor = _cache.get(key)
  299. if tensor is None:
  300. tensor = parametrization()
  301. _cache[key] = tensor
  302. return tensor
  303. def get_parametrized(self) -> Tensor:
  304. if torch.jit.is_scripting():
  305. raise RuntimeError('Parametrization is not working with scripting.')
  306. parametrization = self.parametrizations[tensor_name]
  307. if _cache_enabled:
  308. if torch.jit.is_scripting():
  309. # Scripting
  310. raise RuntimeError('Caching is not implemented for scripting. '
  311. 'Either disable caching or avoid scripting.')
  312. elif torch._C._get_tracing_state() is not None:
  313. # Tracing
  314. raise RuntimeError('Cannot trace a model while caching parametrizations.')
  315. else:
  316. return get_cached_parametrization(parametrization)
  317. else:
  318. # If caching is not active, this function just evaluates the parametrization
  319. return parametrization()
  320. def set_original(self, value: Tensor) -> None:
  321. if torch.jit.is_scripting():
  322. raise RuntimeError('Parametrization is not working with scripting.')
  323. self.parametrizations[tensor_name].right_inverse(value)
  324. setattr(module.__class__, tensor_name, property(get_parametrized, set_original))
  325. def register_parametrization(
  326. module: Module, tensor_name: str, parametrization: Module, *, unsafe: bool = False,
  327. ) -> Module:
  328. r"""Adds a parametrization to a tensor in a module.
  329. Assume that ``tensor_name="weight"`` for simplicity. When accessing ``module.weight``,
  330. the module will return the parametrized version ``parametrization(module.weight)``.
  331. If the original tensor requires a gradient, the backward pass will differentiate
  332. through :attr:`parametrization`, and the optimizer will update the tensor accordingly.
  333. The first time that a module registers a parametrization, this function will add an attribute
  334. ``parametrizations`` to the module of type :class:`~ParametrizationList`.
  335. The list of parametrizations on the tensor ``weight`` will be accessible under
  336. ``module.parametrizations.weight``.
  337. The original tensor will be accessible under
  338. ``module.parametrizations.weight.original``.
  339. Parametrizations may be concatenated by registering several parametrizations
  340. on the same attribute.
  341. The training mode of a registered parametrization is updated on registration
  342. to match the training mode of the host module
  343. Parametrized parameters and buffers have an inbuilt caching system that can be activated
  344. using the context manager :func:`cached`.
  345. A :attr:`parametrization` may optionally implement a method with signature
  346. .. code-block:: python
  347. def right_inverse(self, X: Tensor) -> Union[Tensor, Sequence[Tensor]]
  348. This method is called on the unparametrized tensor when the first parametrization
  349. is registered to compute the initial value of the original tensor.
  350. If this method is not implemented, the original tensor will be just the unparametrized tensor.
  351. If all the parametrizations registered on a tensor implement `right_inverse` it is possible
  352. to initialize a parametrized tensor by assigning to it, as shown in the example below.
  353. It is possible for the first parametrization to depend on several inputs.
  354. This may be implemented returning a tuple of tensors from ``right_inverse``
  355. (see the example implementation of a ``RankOne`` parametrization below).
  356. In this case, the unconstrained tensors are also located under ``module.parametrizations.weight``
  357. with names ``original0``, ``original1``,...
  358. .. note::
  359. If unsafe=False (default) both the forward and right_inverse methods will be called
  360. once to perform a number of consistency checks.
  361. If unsafe=True, then right_inverse will be called if the tensor is not parametrized,
  362. and nothing will be called otherwise.
  363. .. note::
  364. In most situations, ``right_inverse`` will be a function such that
  365. ``forward(right_inverse(X)) == X`` (see
  366. `right inverse <https://en.wikipedia.org/wiki/Inverse_function#Right_inverses>`_).
  367. Sometimes, when the parametrization is not surjective, it may be reasonable
  368. to relax this.
  369. .. warning::
  370. If a parametrization depends on several inputs, :func:`~register_parametrization`
  371. will register a number of new parameters. If such parametrization is registered
  372. after the optimizer is created, these new parameters will need to be added manually
  373. to the optimizer. See :meth:`torch.Optimizer.add_param_group`.
  374. Args:
  375. module (nn.Module): module on which to register the parametrization
  376. tensor_name (str): name of the parameter or buffer on which to register
  377. the parametrization
  378. parametrization (nn.Module): the parametrization to register
  379. Keyword args:
  380. unsafe (bool): a boolean flag that denotes whether the parametrization
  381. may change the dtype and shape of the tensor. Default: `False`
  382. Warning: the parametrization is not checked for consistency upon registration.
  383. Enable this flag at your own risk.
  384. Raises:
  385. ValueError: if the module does not have a parameter or a buffer named :attr:`tensor_name`
  386. Examples:
  387. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
  388. >>> import torch
  389. >>> import torch.nn as nn
  390. >>> import torch.nn.utils.parametrize as P
  391. >>>
  392. >>> class Symmetric(nn.Module):
  393. >>> def forward(self, X):
  394. >>> return X.triu() + X.triu(1).T # Return a symmetric matrix
  395. >>>
  396. >>> def right_inverse(self, A):
  397. >>> return A.triu()
  398. >>>
  399. >>> m = nn.Linear(5, 5)
  400. >>> P.register_parametrization(m, "weight", Symmetric())
  401. >>> print(torch.allclose(m.weight, m.weight.T)) # m.weight is now symmetric
  402. True
  403. >>> A = torch.rand(5, 5)
  404. >>> A = A + A.T # A is now symmetric
  405. >>> m.weight = A # Initialize the weight to be the symmetric matrix A
  406. >>> print(torch.allclose(m.weight, A))
  407. True
  408. >>> class RankOne(nn.Module):
  409. >>> def forward(self, x, y):
  410. >>> # Form a rank 1 matrix multiplying two vectors
  411. >>> return x.unsqueeze(-1) @ y.unsqueeze(-2)
  412. >>>
  413. >>> def right_inverse(self, Z):
  414. >>> # Project Z onto the rank 1 matrices
  415. >>> U, S, Vh = torch.linalg.svd(Z, full_matrices=False)
  416. >>> # Return rescaled singular vectors
  417. >>> s0_sqrt = S[0].sqrt().unsqueeze(-1)
  418. >>> return U[..., :, 0] * s0_sqrt, Vh[..., 0, :] * s0_sqrt
  419. >>>
  420. >>> linear_rank_one = P.register_parametrization(nn.Linear(4, 4), "weight", RankOne())
  421. >>> print(torch.linalg.matrix_rank(linear_rank_one.weight).item())
  422. 1
  423. """
  424. parametrization.train(module.training)
  425. if is_parametrized(module, tensor_name):
  426. # Correctness checks.
  427. # If A is the space of tensors with shape and dtype equal to module.weight
  428. # we check that parametrization.forward and parametrization.right_inverse are
  429. # functions from A to A
  430. if not unsafe:
  431. Y = getattr(module, tensor_name)
  432. X = parametrization(Y)
  433. if not isinstance(X, Tensor):
  434. raise ValueError(
  435. f"A parametrization must return a tensor. Got {type(X).__name__}."
  436. )
  437. if X.dtype != Y.dtype:
  438. raise ValueError(
  439. "Registering a parametrization may not change the dtype of the tensor, unless the `unsafe` flag is enabled.\n"
  440. f"module.{tensor_name}.dtype: {Y.dtype}\n"
  441. f"parametrization(module.{tensor_name}).dtype: {X.dtype}"
  442. )
  443. if X.shape != Y.shape:
  444. raise ValueError(
  445. "Registering a parametrization may not change the shape of the tensor, unless the `unsafe` flag is enabled.\n"
  446. f"module.{tensor_name}.shape: {Y.shape}\n"
  447. f"parametrization(module.{tensor_name}).shape: {X.shape}"
  448. )
  449. if hasattr(parametrization, "right_inverse"):
  450. try:
  451. Z = parametrization.right_inverse(X) # type: ignore[operator]
  452. except NotImplementedError:
  453. pass
  454. else:
  455. if not isinstance(Z, Tensor):
  456. raise ValueError(
  457. f"parametrization.right_inverse must return a tensor. Got: {type(Z).__name__}"
  458. )
  459. if Z.dtype != Y.dtype:
  460. raise ValueError(
  461. "The tensor returned by parametrization.right_inverse must have the same dtype "
  462. f"as module.{tensor_name}, unless the `unsafe` flag is enabled.\n"
  463. f"module.{tensor_name}.dtype: {Y.dtype}\n"
  464. f"returned dtype: {Z.dtype}"
  465. )
  466. if Z.shape != Y.shape:
  467. raise ValueError(
  468. "The tensor returned by parametrization.right_inverse must have the same shape "
  469. f"as module.{tensor_name}, unless the `unsafe` flag is enabled.\n"
  470. f"module.{tensor_name}.shape: {Y.shape}\n"
  471. f"returned shape: {Z.shape}"
  472. )
  473. # else right_inverse is assumed to be the identity
  474. # add the new parametrization to the parametrization list
  475. assert isinstance(module.parametrizations, ModuleDict) # Make mypy happy
  476. module.parametrizations[tensor_name].append(parametrization)
  477. # If unsafe was True in previous parametrization, keep it enabled
  478. module.parametrizations[tensor_name].unsafe |= unsafe # type: ignore[index, union-attr]
  479. elif tensor_name in module._buffers or tensor_name in module._parameters:
  480. # Set the parametrization mechanism
  481. # Fetch the original buffer or parameter
  482. original = getattr(module, tensor_name)
  483. # We create this early to check for possible errors
  484. parametrizations = ParametrizationList([parametrization], original, unsafe=unsafe)
  485. # Delete the previous parameter or buffer
  486. delattr(module, tensor_name)
  487. # If this is the first parametrization registered on the module,
  488. # we prepare the module to inject the property
  489. if not is_parametrized(module):
  490. # Change the class
  491. _inject_new_class(module)
  492. # Inject a ``ModuleDict`` into the instance under module.parametrizations
  493. module.parametrizations = ModuleDict()
  494. # Add a property into the class
  495. _inject_property(module, tensor_name)
  496. # Add a ParametrizationList
  497. assert isinstance(module.parametrizations, ModuleDict) # Make mypy happy
  498. module.parametrizations[tensor_name] = parametrizations
  499. else:
  500. raise ValueError(
  501. f"Module '{module}' does not have a parameter, a buffer, or a "
  502. f"parametrized element with name '{tensor_name}'"
  503. )
  504. return module
  505. def is_parametrized(module: Module, tensor_name: Optional[str] = None) -> bool:
  506. r"""Returns ``True`` if module has an active parametrization.
  507. If the argument :attr:`tensor_name` is specified, returns ``True`` if
  508. ``module[tensor_name]`` is parametrized.
  509. Args:
  510. module (nn.Module): module to query
  511. tensor_name (str, optional): attribute in the module to query
  512. Default: ``None``
  513. """
  514. parametrizations = getattr(module, "parametrizations", None)
  515. if parametrizations is None or not isinstance(parametrizations, ModuleDict):
  516. return False
  517. if tensor_name is None:
  518. # Check that there is at least one parametrized buffer or Parameter
  519. return len(parametrizations) > 0
  520. else:
  521. return tensor_name in parametrizations
  522. def remove_parametrizations(
  523. module: Module, tensor_name: str, leave_parametrized: bool = True
  524. ) -> Module:
  525. r"""Removes the parametrizations on a tensor in a module.
  526. - If ``leave_parametrized=True``, ``module[tensor_name]`` will be set to
  527. its current output. In this case, the parametrization shall not change the ``dtype``
  528. of the tensor.
  529. - If ``leave_parametrized=False``, ``module[tensor_name]`` will be set to
  530. the unparametrised tensor in ``module.parametrizations[tensor_name].original``.
  531. This is only possible when the parametrization depends on just one tensor.
  532. Args:
  533. module (nn.Module): module from which remove the parametrization
  534. tensor_name (str): name of the parametrization to be removed
  535. leave_parametrized (bool, optional): leave the attribute :attr:`tensor_name` parametrized.
  536. Default: ``True``
  537. Returns:
  538. Module: module
  539. Raises:
  540. ValueError: if ``module[tensor_name]`` is not parametrized
  541. ValueError: if ``leave_parametrized=False`` and the parametrization depends on several tensors
  542. """
  543. if not is_parametrized(module, tensor_name):
  544. raise ValueError(f"Module {module} does not have a parametrization on {tensor_name}")
  545. # Fetch the original tensor
  546. assert isinstance(module.parametrizations, ModuleDict) # Make mypy happy
  547. parametrizations = module.parametrizations[tensor_name]
  548. if parametrizations.is_tensor:
  549. original = parametrizations.original
  550. if leave_parametrized:
  551. with torch.no_grad():
  552. t = getattr(module, tensor_name)
  553. # We know they have the same dtype because we have checked this when registering the
  554. # parametrizations. As such, we can use set_
  555. # We do this so that the parameter does not to change the id()
  556. # This way the user does not need to update the optimizer
  557. with torch.no_grad():
  558. if type(original) is torch.Tensor:
  559. original.set_(t)
  560. else:
  561. try:
  562. original.set_(t)
  563. except RuntimeError as e:
  564. # TODO: Fix this for tensor subclasses that are parameters:
  565. # RuntimeError: set_storage is not allowed on a Tensor created from .data or .detach().
  566. raise RuntimeError("Calling remove_parametrizations() with leave_parametrized=True "
  567. "for a parameter that is an instance of a tensor subclass requires "
  568. "set_() to be implemented correctly for the tensor subclass. Either "
  569. "set leave_parametrized=False or provide a working implementation for "
  570. "set_() in the tensor subclass.") from e
  571. else:
  572. if leave_parametrized:
  573. # We cannot use no_grad because we need to know whether one or more
  574. # original tensors required grad
  575. t = getattr(module, tensor_name)
  576. # We'll have to trust the user to add it to the optimizer
  577. original = Parameter(t) if t.requires_grad else t
  578. else:
  579. raise ValueError("Cannot leave unparametrized (`leave_parametrized=False`) a tensor "
  580. "that is parametrized in terms of a sequence of tensors.")
  581. # Delete the property that manages the parametrization
  582. delattr(module.__class__, tensor_name)
  583. # Delete the ParametrizationList
  584. del module.parametrizations[tensor_name]
  585. # Restore the parameter / buffer into the main class
  586. _register_parameter_or_buffer(module, tensor_name, original)
  587. # Roll back the parametrized class if no other buffer or parameter
  588. # is currently parametrized in this class
  589. if not is_parametrized(module):
  590. delattr(module, "parametrizations")
  591. # Restore class
  592. orig_cls = module.__class__.__bases__[0]
  593. module.__class__ = orig_cls
  594. return module
  595. def type_before_parametrizations(module: Module) -> type:
  596. r"""Returns the module type before parametrizations were applied and if not,
  597. then it returns the module type.
  598. Args:
  599. module (nn.Module): module to get type of
  600. """
  601. if is_parametrized(module):
  602. return module.__class__.__bases__[0]
  603. else:
  604. return type(module)
  605. def transfer_parametrizations_and_params(
  606. from_module: Module, to_module: Module, tensor_name: Optional[str] = None
  607. ) -> Module:
  608. r"""Transfers parametrizations and the parameters they parametrize from from_module
  609. to to_module. If tensor_name is specified, only transfers the specified parameter, otherwise
  610. transfers all parametrized parameters. If those parameters do not exist in to_module, it will create them.
  611. Does nothing if from_module is not parametrized.
  612. Args:
  613. from_module (nn.Module): module to transfer from
  614. to_module (nn.Module): module to transfer to
  615. tensor_name (str, optional): parameter to transfer
  616. Returns:
  617. Module: to_module
  618. """
  619. if is_parametrized(from_module):
  620. assert isinstance(from_module.parametrizations, ModuleDict) # for mypy
  621. # get list of all params or the single param to transfer
  622. parameters_to_transfer: Union[list, ModuleDict] = (
  623. from_module.parametrizations if tensor_name is None else [tensor_name]
  624. )
  625. assert hasattr(parameters_to_transfer, "__iter__") # for mypy
  626. for parameter_name in parameters_to_transfer:
  627. # initialize the to-be-transfered param in to_module if it doesn't exist already
  628. if not hasattr(to_module, parameter_name):
  629. setattr(
  630. to_module,
  631. parameter_name,
  632. Parameter(getattr(from_module, parameter_name)),
  633. )
  634. # apply the params's parametrizations to to_module
  635. for param_func in from_module.parametrizations[parameter_name]:
  636. register_parametrization(to_module, parameter_name, param_func)
  637. assert isinstance(to_module.parametrizations, ModuleDict) # for mypy
  638. # make values match, original values can be stored in either original or
  639. # original0, original1..., need to check both cases
  640. if hasattr(from_module.parametrizations[parameter_name], "original"):
  641. to_module.parametrizations[parameter_name].original = \
  642. from_module.parametrizations[parameter_name].original
  643. else:
  644. num = 0
  645. orig_num = "original" + str(num)
  646. # loop through each original# until all values have been set
  647. while hasattr(from_module.parametrizations[parameter_name], orig_num):
  648. setattr(
  649. to_module.parametrizations[parameter_name],
  650. orig_num,
  651. getattr(from_module.parametrizations[parameter_name], orig_num),
  652. )
  653. num = num + 1
  654. orig_num = "original" + str(num)
  655. return to_module