parametrize.py 35 KB

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