parametrizations.py 25 KB

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