parametrizations.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. # mypy: allow-untyped-defs
  2. from enum import auto, Enum
  3. from typing import Optional
  4. import torch
  5. import torch.nn.functional as F
  6. from torch import Tensor
  7. from torch.nn.modules import Module
  8. from torch.nn.utils import parametrize
  9. __all__ = ["orthogonal", "spectral_norm", "weight_norm"]
  10. def _is_orthogonal(Q, eps=None):
  11. n, k = Q.size(-2), Q.size(-1)
  12. Id = torch.eye(k, dtype=Q.dtype, device=Q.device)
  13. # A reasonable eps, but not too large
  14. eps = 10.0 * n * torch.finfo(Q.dtype).eps
  15. return torch.allclose(Q.mH @ Q, Id, atol=eps)
  16. def _make_orthogonal(A):
  17. """Assume that A is a tall matrix.
  18. Compute the Q factor s.t. A = QR (A may be complex) and diag(R) is real and non-negative.
  19. """
  20. X, tau = torch.geqrf(A)
  21. Q = torch.linalg.householder_product(X, tau)
  22. # The diagonal of X is the diagonal of R (which is always real) so we normalise by its signs
  23. Q *= X.diagonal(dim1=-2, dim2=-1).sgn().unsqueeze(-2)
  24. return Q
  25. class _OrthMaps(Enum):
  26. matrix_exp = auto()
  27. cayley = auto()
  28. householder = auto()
  29. class _Orthogonal(Module):
  30. base: Tensor
  31. def __init__(
  32. self, weight, orthogonal_map: _OrthMaps, *, use_trivialization=True
  33. ) -> None:
  34. super().__init__()
  35. # Note [Householder complex]
  36. # For complex tensors, it is not possible to compute the tensor `tau` necessary for
  37. # linalg.householder_product from the reflectors.
  38. # To see this, note that the reflectors have a shape like:
  39. # 0 0 0
  40. # * 0 0
  41. # * * 0
  42. # which, for complex matrices, give n(n-1) (real) parameters. Now, you need n^2 parameters
  43. # to parametrize the unitary matrices. Saving tau on its own does not work either, because
  44. # not every combination of `(A, tau)` gives a unitary matrix, meaning that if we optimise
  45. # them as independent tensors we would not maintain the constraint
  46. # An equivalent reasoning holds for rectangular matrices
  47. if weight.is_complex() and orthogonal_map == _OrthMaps.householder:
  48. raise ValueError(
  49. "The householder parametrization does not support complex tensors."
  50. )
  51. self.shape = weight.shape
  52. self.orthogonal_map = orthogonal_map
  53. if use_trivialization:
  54. self.register_buffer("base", None)
  55. def forward(self, X: torch.Tensor) -> torch.Tensor:
  56. n, k = X.size(-2), X.size(-1)
  57. transposed = n < k
  58. if transposed:
  59. X = X.mT
  60. n, k = k, n
  61. # Here n > k and X is a tall matrix
  62. if (
  63. self.orthogonal_map == _OrthMaps.matrix_exp
  64. or self.orthogonal_map == _OrthMaps.cayley
  65. ):
  66. # We just need n x k - k(k-1)/2 parameters
  67. X = X.tril()
  68. if n != k:
  69. # Embed into a square matrix
  70. X = torch.cat(
  71. [X, X.new_zeros(n, n - k).expand(*X.shape[:-2], -1, -1)], dim=-1
  72. )
  73. A = X - X.mH
  74. # A is skew-symmetric (or skew-hermitian)
  75. if self.orthogonal_map == _OrthMaps.matrix_exp:
  76. Q = torch.matrix_exp(A)
  77. elif self.orthogonal_map == _OrthMaps.cayley:
  78. # Computes the Cayley retraction (I+A/2)(I-A/2)^{-1}
  79. Id = torch.eye(n, dtype=A.dtype, device=A.device)
  80. Q = torch.linalg.solve(
  81. torch.add(Id, A, alpha=-0.5), torch.add(Id, A, alpha=0.5)
  82. )
  83. # Q is now orthogonal (or unitary) of size (..., n, n)
  84. if n != k:
  85. Q = Q[..., :k]
  86. # Q is now the size of the X (albeit perhaps transposed)
  87. else:
  88. # X is real here, as we do not support householder with complex numbers
  89. A = X.tril(diagonal=-1)
  90. tau = 2.0 / (1.0 + (A * A).sum(dim=-2))
  91. Q = torch.linalg.householder_product(A, tau)
  92. # The diagonal of X is 1's and -1's
  93. # We do not want to differentiate through this or update the diagonal of X hence the casting
  94. Q = Q * X.diagonal(dim1=-2, dim2=-1).int().unsqueeze(-2)
  95. if hasattr(self, "base"):
  96. Q = self.base @ Q
  97. if transposed:
  98. Q = Q.mT
  99. return Q # type: ignore[possibly-undefined]
  100. @torch.autograd.no_grad()
  101. def right_inverse(self, Q: torch.Tensor) -> torch.Tensor:
  102. if Q.shape != self.shape:
  103. raise ValueError(
  104. f"Expected a matrix or batch of matrices of shape {self.shape}. "
  105. f"Got a tensor of shape {Q.shape}."
  106. )
  107. Q_init = Q
  108. n, k = Q.size(-2), Q.size(-1)
  109. transpose = n < k
  110. if transpose:
  111. Q = Q.mT
  112. n, k = k, n
  113. # We always make sure to always copy Q in every path
  114. if not hasattr(self, "base"):
  115. # Note [right_inverse expm cayley]
  116. # If we do not have use_trivialization=True, we just implement the inverse of the forward
  117. # map for the Householder. To see why, think that for the Cayley map,
  118. # we would need to find the matrix X \in R^{n x k} such that:
  119. # Y = torch.cat([X.tril(), X.new_zeros(n, n - k).expand(*X.shape[:-2], -1, -1)], dim=-1)
  120. # A = Y - Y.mH
  121. # cayley(A)[:, :k]
  122. # gives the original tensor. It is not clear how to do this.
  123. # Perhaps via some algebraic manipulation involving the QR like that of
  124. # Corollary 2.2 in Edelman, Arias and Smith?
  125. if (
  126. self.orthogonal_map == _OrthMaps.cayley
  127. or self.orthogonal_map == _OrthMaps.matrix_exp
  128. ):
  129. raise NotImplementedError(
  130. "It is not possible to assign to the matrix exponential "
  131. "or the Cayley parametrizations when use_trivialization=False."
  132. )
  133. # If parametrization == _OrthMaps.householder, make Q orthogonal via the QR decomposition.
  134. # Here Q is always real because we do not support householder and complex matrices.
  135. # See note [Householder complex]
  136. A, tau = torch.geqrf(Q)
  137. # We want to have a decomposition X = QR with diag(R) > 0, as otherwise we could
  138. # decompose an orthogonal matrix Q as Q = (-Q)@(-Id), which is a valid QR decomposition
  139. # The diagonal of Q is the diagonal of R from the qr decomposition
  140. A.diagonal(dim1=-2, dim2=-1).sign_()
  141. # Equality with zero is ok because LAPACK returns exactly zero when it does not want
  142. # to use a particular reflection
  143. A.diagonal(dim1=-2, dim2=-1)[tau == 0.0] *= -1
  144. return A.mT if transpose else A
  145. else:
  146. if n == k:
  147. # We check whether Q is orthogonal
  148. if not _is_orthogonal(Q):
  149. Q = _make_orthogonal(Q)
  150. else: # Is orthogonal
  151. Q = Q.clone()
  152. else:
  153. # Complete Q into a full n x n orthogonal matrix
  154. N = torch.randn(
  155. *(Q.size()[:-2] + (n, n - k)), dtype=Q.dtype, device=Q.device
  156. )
  157. Q = torch.cat([Q, N], dim=-1)
  158. Q = _make_orthogonal(Q)
  159. self.base = Q
  160. # It is necessary to return the -Id, as we use the diagonal for the
  161. # Householder parametrization. Using -Id makes:
  162. # householder(torch.zeros(m,n)) == torch.eye(m,n)
  163. # Poor man's version of eye_like
  164. neg_Id = torch.zeros_like(Q_init)
  165. neg_Id.diagonal(dim1=-2, dim2=-1).fill_(-1.0)
  166. return neg_Id
  167. def orthogonal(
  168. module: Module,
  169. name: str = "weight",
  170. orthogonal_map: Optional[str] = None,
  171. *,
  172. use_trivialization: bool = True,
  173. ) -> Module:
  174. r"""Apply an orthogonal or unitary parametrization to a matrix or a batch of matrices.
  175. Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`, the parametrized
  176. matrix :math:`Q \in \mathbb{K}^{m \times n}` is **orthogonal** as
  177. .. math::
  178. \begin{align*}
  179. Q^{\text{H}}Q &= \mathrm{I}_n \mathrlap{\qquad \text{if }m \geq n}\\
  180. QQ^{\text{H}} &= \mathrm{I}_m \mathrlap{\qquad \text{if }m < n}
  181. \end{align*}
  182. where :math:`Q^{\text{H}}` is the conjugate transpose when :math:`Q` is complex
  183. and the transpose when :math:`Q` is real-valued, and
  184. :math:`\mathrm{I}_n` is the `n`-dimensional identity matrix.
  185. In plain words, :math:`Q` will have orthonormal columns whenever :math:`m \geq n`
  186. and orthonormal rows otherwise.
  187. If the tensor has more than two dimensions, we consider it as a batch of matrices of shape `(..., m, n)`.
  188. The matrix :math:`Q` may be parametrized via three different ``orthogonal_map`` in terms of the original tensor:
  189. - ``"matrix_exp"``/``"cayley"``:
  190. the :func:`~torch.matrix_exp` :math:`Q = \exp(A)` and the `Cayley map`_
  191. :math:`Q = (\mathrm{I}_n + A/2)(\mathrm{I}_n - A/2)^{-1}` are applied to a skew-symmetric
  192. :math:`A` to give an orthogonal matrix.
  193. - ``"householder"``: computes a product of Householder reflectors
  194. (:func:`~torch.linalg.householder_product`).
  195. ``"matrix_exp"``/``"cayley"`` often make the parametrized weight converge faster than
  196. ``"householder"``, but they are slower to compute for very thin or very wide matrices.
  197. If ``use_trivialization=True`` (default), the parametrization implements the "Dynamic Trivialization Framework",
  198. where an extra matrix :math:`B \in \mathbb{K}^{n \times n}` is stored under
  199. ``module.parametrizations.weight[0].base``. This helps the
  200. convergence of the parametrized layer at the expense of some extra memory use.
  201. See `Trivializations for Gradient-Based Optimization on Manifolds`_ .
  202. Initial value of :math:`Q`:
  203. If the original tensor is not parametrized and ``use_trivialization=True`` (default), the initial value
  204. of :math:`Q` is that of the original tensor if it is orthogonal (or unitary in the complex case)
  205. and it is orthogonalized via the QR decomposition otherwise (see :func:`torch.linalg.qr`).
  206. Same happens when it is not parametrized and ``orthogonal_map="householder"`` even when ``use_trivialization=False``.
  207. Otherwise, the initial value is the result of the composition of all the registered
  208. parametrizations applied to the original tensor.
  209. .. note::
  210. This function is implemented using the parametrization functionality
  211. in :func:`~torch.nn.utils.parametrize.register_parametrization`.
  212. .. _`Cayley map`: https://en.wikipedia.org/wiki/Cayley_transform#Matrix_map
  213. .. _`Trivializations for Gradient-Based Optimization on Manifolds`: https://arxiv.org/abs/1909.09501
  214. Args:
  215. module (nn.Module): module on which to register the parametrization.
  216. name (str, optional): name of the tensor to make orthogonal. Default: ``"weight"``.
  217. orthogonal_map (str, optional): One of the following: ``"matrix_exp"``, ``"cayley"``, ``"householder"``.
  218. Default: ``"matrix_exp"`` if the matrix is square or complex, ``"householder"`` otherwise.
  219. use_trivialization (bool, optional): whether to use the dynamic trivialization framework.
  220. Default: ``True``.
  221. Returns:
  222. The original module with an orthogonal parametrization registered to the specified
  223. weight
  224. Example::
  225. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
  226. >>> orth_linear = orthogonal(nn.Linear(20, 40))
  227. >>> orth_linear
  228. ParametrizedLinear(
  229. in_features=20, out_features=40, bias=True
  230. (parametrizations): ModuleDict(
  231. (weight): ParametrizationList(
  232. (0): _Orthogonal()
  233. )
  234. )
  235. )
  236. >>> # xdoctest: +IGNORE_WANT
  237. >>> Q = orth_linear.weight
  238. >>> torch.dist(Q.T @ Q, torch.eye(20))
  239. tensor(4.9332e-07)
  240. """
  241. weight = getattr(module, name, None)
  242. if not isinstance(weight, Tensor):
  243. raise ValueError(
  244. f"Module '{module}' has no parameter or buffer with name '{name}'"
  245. )
  246. # We could implement this for 1-dim tensors as the maps on the sphere
  247. # but I believe it'd bite more people than it'd help
  248. if weight.ndim < 2:
  249. raise ValueError(
  250. "Expected a matrix or batch of matrices. "
  251. f"Got a tensor of {weight.ndim} dimensions."
  252. )
  253. if orthogonal_map is None:
  254. orthogonal_map = (
  255. "matrix_exp"
  256. if weight.size(-2) == weight.size(-1) or weight.is_complex()
  257. else "householder"
  258. )
  259. orth_enum = getattr(_OrthMaps, orthogonal_map, None)
  260. if orth_enum is None:
  261. raise ValueError(
  262. 'orthogonal_map has to be one of "matrix_exp", "cayley", "householder". '
  263. f"Got: {orthogonal_map}"
  264. )
  265. orth = _Orthogonal(weight, orth_enum, use_trivialization=use_trivialization)
  266. parametrize.register_parametrization(module, name, orth, unsafe=True)
  267. return module
  268. class _WeightNorm(Module):
  269. def __init__(
  270. self,
  271. dim: Optional[int] = 0,
  272. ) -> None:
  273. super().__init__()
  274. if dim is None:
  275. dim = -1
  276. self.dim = dim
  277. def forward(self, weight_g, weight_v):
  278. return torch._weight_norm(weight_v, weight_g, self.dim)
  279. def right_inverse(self, weight):
  280. weight_g = torch.norm_except_dim(weight, 2, self.dim)
  281. weight_v = weight
  282. return weight_g, weight_v
  283. def weight_norm(module: Module, name: str = "weight", dim: int = 0):
  284. r"""Apply weight normalization to a parameter in the given module.
  285. .. math::
  286. \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|}
  287. Weight normalization is a reparameterization that decouples the magnitude
  288. of a weight tensor from its direction. This replaces the parameter specified
  289. by :attr:`name` with two parameters: one specifying the magnitude
  290. and one specifying the direction.
  291. By default, with ``dim=0``, the norm is computed independently per output
  292. channel/plane. To compute a norm over the entire weight tensor, use
  293. ``dim=None``.
  294. See https://arxiv.org/abs/1602.07868
  295. Args:
  296. module (Module): containing module
  297. name (str, optional): name of weight parameter
  298. dim (int, optional): dimension over which to compute the norm
  299. Returns:
  300. The original module with the weight norm hook
  301. Example::
  302. >>> m = weight_norm(nn.Linear(20, 40), name='weight')
  303. >>> m
  304. ParametrizedLinear(
  305. in_features=20, out_features=40, bias=True
  306. (parametrizations): ModuleDict(
  307. (weight): ParametrizationList(
  308. (0): _WeightNorm()
  309. )
  310. )
  311. )
  312. >>> m.parametrizations.weight.original0.size()
  313. torch.Size([40, 1])
  314. >>> m.parametrizations.weight.original1.size()
  315. torch.Size([40, 20])
  316. """
  317. _weight_norm = _WeightNorm(dim)
  318. parametrize.register_parametrization(module, name, _weight_norm, unsafe=True)
  319. def _weight_norm_compat_hook(
  320. state_dict,
  321. prefix,
  322. local_metadata,
  323. strict,
  324. missing_keys,
  325. unexpected_keys,
  326. error_msgs,
  327. ):
  328. g_key = f"{prefix}{name}_g"
  329. v_key = f"{prefix}{name}_v"
  330. if g_key in state_dict and v_key in state_dict:
  331. original0 = state_dict.pop(g_key)
  332. original1 = state_dict.pop(v_key)
  333. state_dict[f"{prefix}parametrizations.{name}.original0"] = original0
  334. state_dict[f"{prefix}parametrizations.{name}.original1"] = original1
  335. module._register_load_state_dict_pre_hook(_weight_norm_compat_hook)
  336. return module
  337. class _SpectralNorm(Module):
  338. def __init__(
  339. self,
  340. weight: torch.Tensor,
  341. n_power_iterations: int = 1,
  342. dim: int = 0,
  343. eps: float = 1e-12,
  344. ) -> None:
  345. super().__init__()
  346. ndim = weight.ndim
  347. if dim >= ndim or dim < -ndim:
  348. raise IndexError(
  349. "Dimension out of range (expected to be in range of "
  350. f"[-{ndim}, {ndim - 1}] but got {dim})"
  351. )
  352. if n_power_iterations <= 0:
  353. raise ValueError(
  354. "Expected n_power_iterations to be positive, but "
  355. f"got n_power_iterations={n_power_iterations}"
  356. )
  357. self.dim = dim if dim >= 0 else dim + ndim
  358. self.eps = eps
  359. if ndim > 1:
  360. # For ndim == 1 we do not need to approximate anything (see _SpectralNorm.forward)
  361. self.n_power_iterations = n_power_iterations
  362. weight_mat = self._reshape_weight_to_matrix(weight)
  363. h, w = weight_mat.size()
  364. u = weight_mat.new_empty(h).normal_(0, 1)
  365. v = weight_mat.new_empty(w).normal_(0, 1)
  366. self.register_buffer("_u", F.normalize(u, dim=0, eps=self.eps))
  367. self.register_buffer("_v", F.normalize(v, dim=0, eps=self.eps))
  368. # Start with u, v initialized to some reasonable values by performing a number
  369. # of iterations of the power method
  370. self._power_method(weight_mat, 15)
  371. def _reshape_weight_to_matrix(self, weight: torch.Tensor) -> torch.Tensor:
  372. # Precondition
  373. assert weight.ndim > 1
  374. if self.dim != 0:
  375. # permute dim to front
  376. weight = weight.permute(
  377. self.dim, *(d for d in range(weight.dim()) if d != self.dim)
  378. )
  379. return weight.flatten(1)
  380. @torch.autograd.no_grad()
  381. def _power_method(self, weight_mat: torch.Tensor, n_power_iterations: int) -> None:
  382. # See original note at torch/nn/utils/spectral_norm.py
  383. # NB: If `do_power_iteration` is set, the `u` and `v` vectors are
  384. # updated in power iteration **in-place**. This is very important
  385. # because in `DataParallel` forward, the vectors (being buffers) are
  386. # broadcast from the parallelized module to each module replica,
  387. # which is a new module object created on the fly. And each replica
  388. # runs its own spectral norm power iteration. So simply assigning
  389. # the updated vectors to the module this function runs on will cause
  390. # the update to be lost forever. And the next time the parallelized
  391. # module is replicated, the same randomly initialized vectors are
  392. # broadcast and used!
  393. #
  394. # Therefore, to make the change propagate back, we rely on two
  395. # important behaviors (also enforced via tests):
  396. # 1. `DataParallel` doesn't clone storage if the broadcast tensor
  397. # is already on correct device; and it makes sure that the
  398. # parallelized module is already on `device[0]`.
  399. # 2. If the out tensor in `out=` kwarg has correct shape, it will
  400. # just fill in the values.
  401. # Therefore, since the same power iteration is performed on all
  402. # devices, simply updating the tensors in-place will make sure that
  403. # the module replica on `device[0]` will update the _u vector on the
  404. # parallelized module (by shared storage).
  405. #
  406. # However, after we update `u` and `v` in-place, we need to **clone**
  407. # them before using them to normalize the weight. This is to support
  408. # backproping through two forward passes, e.g., the common pattern in
  409. # GAN training: loss = D(real) - D(fake). Otherwise, engine will
  410. # complain that variables needed to do backward for the first forward
  411. # (i.e., the `u` and `v` vectors) are changed in the second forward.
  412. # Precondition
  413. assert weight_mat.ndim > 1
  414. for _ in range(n_power_iterations):
  415. # Spectral norm of weight equals to `u^T W v`, where `u` and `v`
  416. # are the first left and right singular vectors.
  417. # This power iteration produces approximations of `u` and `v`.
  418. self._u = F.normalize(
  419. torch.mv(weight_mat, self._v), # type: ignore[has-type]
  420. dim=0,
  421. eps=self.eps,
  422. out=self._u, # type: ignore[has-type]
  423. )
  424. self._v = F.normalize(
  425. torch.mv(weight_mat.H, self._u), # type: ignore[has-type]
  426. dim=0,
  427. eps=self.eps,
  428. out=self._v, # type: ignore[has-type]
  429. )
  430. def forward(self, weight: torch.Tensor) -> torch.Tensor:
  431. if weight.ndim == 1:
  432. # Faster and more exact path, no need to approximate anything
  433. return F.normalize(weight, dim=0, eps=self.eps)
  434. else:
  435. weight_mat = self._reshape_weight_to_matrix(weight)
  436. if self.training:
  437. self._power_method(weight_mat, self.n_power_iterations)
  438. # See above on why we need to clone
  439. u = self._u.clone(memory_format=torch.contiguous_format)
  440. v = self._v.clone(memory_format=torch.contiguous_format)
  441. # The proper way of computing this should be through F.bilinear, but
  442. # it seems to have some efficiency issues:
  443. # https://github.com/pytorch/pytorch/issues/58093
  444. sigma = torch.vdot(u, torch.mv(weight_mat, v))
  445. return weight / sigma
  446. def right_inverse(self, value: torch.Tensor) -> torch.Tensor:
  447. # we may want to assert here that the passed value already
  448. # satisfies constraints
  449. return value
  450. def spectral_norm(
  451. module: Module,
  452. name: str = "weight",
  453. n_power_iterations: int = 1,
  454. eps: float = 1e-12,
  455. dim: Optional[int] = None,
  456. ) -> Module:
  457. r"""Apply spectral normalization to a parameter in the given module.
  458. .. math::
  459. \mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})},
  460. \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2}
  461. When applied on a vector, it simplifies to
  462. .. math::
  463. \mathbf{x}_{SN} = \dfrac{\mathbf{x}}{\|\mathbf{x}\|_2}
  464. Spectral normalization stabilizes the training of discriminators (critics)
  465. in Generative Adversarial Networks (GANs) by reducing the Lipschitz constant
  466. of the model. :math:`\sigma` is approximated performing one iteration of the
  467. `power method`_ every time the weight is accessed. If the dimension of the
  468. weight tensor is greater than 2, it is reshaped to 2D in power iteration
  469. method to get spectral norm.
  470. See `Spectral Normalization for Generative Adversarial Networks`_ .
  471. .. _`power method`: https://en.wikipedia.org/wiki/Power_iteration
  472. .. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957
  473. .. note::
  474. This function is implemented using the parametrization functionality
  475. in :func:`~torch.nn.utils.parametrize.register_parametrization`. It is a
  476. reimplementation of :func:`torch.nn.utils.spectral_norm`.
  477. .. note::
  478. When this constraint is registered, the singular vectors associated to the largest
  479. singular value are estimated rather than sampled at random. These are then updated
  480. performing :attr:`n_power_iterations` of the `power method`_ whenever the tensor
  481. is accessed with the module on `training` mode.
  482. .. note::
  483. If the `_SpectralNorm` module, i.e., `module.parametrization.weight[idx]`,
  484. is in training mode on removal, it will perform another power iteration.
  485. If you'd like to avoid this iteration, set the module to eval mode
  486. before its removal.
  487. Args:
  488. module (nn.Module): containing module
  489. name (str, optional): name of weight parameter. Default: ``"weight"``.
  490. n_power_iterations (int, optional): number of power iterations to
  491. calculate spectral norm. Default: ``1``.
  492. eps (float, optional): epsilon for numerical stability in
  493. calculating norms. Default: ``1e-12``.
  494. dim (int, optional): dimension corresponding to number of outputs.
  495. Default: ``0``, except for modules that are instances of
  496. ConvTranspose{1,2,3}d, when it is ``1``
  497. Returns:
  498. The original module with a new parametrization registered to the specified
  499. weight
  500. Example::
  501. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
  502. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  503. >>> snm = spectral_norm(nn.Linear(20, 40))
  504. >>> snm
  505. ParametrizedLinear(
  506. in_features=20, out_features=40, bias=True
  507. (parametrizations): ModuleDict(
  508. (weight): ParametrizationList(
  509. (0): _SpectralNorm()
  510. )
  511. )
  512. )
  513. >>> torch.linalg.matrix_norm(snm.weight, 2)
  514. tensor(1.0081, grad_fn=<AmaxBackward0>)
  515. """
  516. weight = getattr(module, name, None)
  517. if not isinstance(weight, Tensor):
  518. raise ValueError(
  519. f"Module '{module}' has no parameter or buffer with name '{name}'"
  520. )
  521. if dim is None:
  522. if isinstance(
  523. module,
  524. (
  525. torch.nn.ConvTranspose1d,
  526. torch.nn.ConvTranspose2d,
  527. torch.nn.ConvTranspose3d,
  528. ),
  529. ):
  530. dim = 1
  531. else:
  532. dim = 0
  533. parametrize.register_parametrization(
  534. module, name, _SpectralNorm(weight, n_power_iterations, dim, eps)
  535. )
  536. return module