{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parametrizations Tutorial\n",
    "\n",
    "**Author**: [Mario Lezcano](https://github.com/lezcano)\n",
    "\n",
    "Regularizing deep-learning models is a surprisingly challenging task.\n",
    "Classical techniques such as penalty methods often fall short when\n",
    "applied on deep models due to the complexity of the function being\n",
    "optimized. This is particularly problematic when working with\n",
    "ill-conditioned models. Examples of these are RNNs trained on long\n",
    "sequences and GANs. A number of techniques have been proposed in recent\n",
    "years to regularize these models and improve their convergence. On\n",
    "recurrent models, it has been proposed to control the singular values of\n",
    "the recurrent kernel for the RNN to be well-conditioned. This can be\n",
    "achieved, for example, by making the recurrent kernel\n",
    "[orthogonal](https://en.wikipedia.org/wiki/Orthogonal_matrix). Another\n",
    "way to regularize recurrent models is via \\\"[weight\n",
    "normalization](https://pytorch.org/docs/stable/generated/torch.nn.utils.weight_norm.html)\\\".\n",
    "This approach proposes to decouple the learning of the parameters from\n",
    "the learning of their norms. To do so, the parameter is divided by its\n",
    "[Frobenius\n",
    "norm](https://en.wikipedia.org/wiki/Matrix_norm#Frobenius_norm) and a\n",
    "separate parameter encoding its norm is learned. A similar\n",
    "regularization was proposed for GANs under the name of \\\"[spectral\n",
    "normalization](https://pytorch.org/docs/stable/generated/torch.nn.utils.spectral_norm.html)\\\".\n",
    "This method controls the Lipschitz constant of the network by dividing\n",
    "its parameters by their [spectral\n",
    "norm](https://en.wikipedia.org/wiki/Matrix_norm#Special_cases), rather\n",
    "than their Frobenius norm.\n",
    "\n",
    "All these methods have a common pattern: they all transform a parameter\n",
    "in an appropriate way before using it. In the first case, they make it\n",
    "orthogonal by using a function that maps matrices to orthogonal\n",
    "matrices. In the case of weight and spectral normalization, they divide\n",
    "the original parameter by its norm.\n",
    "\n",
    "More generally, all these examples use a function to put extra structure\n",
    "on the parameters. In other words, they use a function to constrain the\n",
    "parameters.\n",
    "\n",
    "In this tutorial, you will learn how to implement and use this pattern\n",
    "to put constraints on your model. Doing so is as easy as writing your\n",
    "own `nn.Module`.\n",
    "\n",
    "Requirements: `torch>=1.9.0`\n",
    "\n",
    "## Implementing parametrizations by hand\n",
    "\n",
    "Assume that we want to have a square linear layer with symmetric\n",
    "weights, that is, with weights `X` such that `X = Xᵀ`. One way to do so\n",
    "is to copy the upper-triangular part of the matrix into its\n",
    "lower-triangular part\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.utils.parametrize as parametrize\n",
    "\n",
    "def symmetric(X):\n",
    "    return X.triu() + X.triu(1).transpose(-1, -2)\n",
    "\n",
    "X = torch.rand(3, 3)\n",
    "A = symmetric(X)\n",
    "assert torch.allclose(A, A.T)  # A is symmetric\n",
    "print(A)                       # Quick visual check"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can then use this idea to implement a linear layer with symmetric\n",
    "weights\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class LinearSymmetric(nn.Module):\n",
    "    def __init__(self, n_features):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.rand(n_features, n_features))\n",
    "\n",
    "    def forward(self, x):\n",
    "        A = symmetric(self.weight)\n",
    "        return x @ A"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The layer can be then used as a regular linear layer\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = LinearSymmetric(3)\n",
    "out = layer(torch.rand(8, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This implementation, although correct and self-contained, presents a\n",
    "number of problems:\n",
    "\n",
    "1)  It reimplements the layer. We had to implement the linear layer as\n",
    "    `x @ A`. This is not very problematic for a linear layer, but\n",
    "    imagine having to reimplement a CNN or a Transformer\\...\n",
    "2)  It does not separate the layer and the parametrization. If the\n",
    "    parametrization were more difficult, we would have to rewrite its\n",
    "    code for each layer that we want to use it in.\n",
    "3)  It recomputes the parametrization every time we use the layer. If we\n",
    "    use the layer several times during the forward pass, (imagine the\n",
    "    recurrent kernel of an RNN), it would compute the same `A` every\n",
    "    time that the layer is called.\n",
    "\n",
    "# Introduction to parametrizations\n",
    "\n",
    "Parametrizations can solve all these problems as well as others.\n",
    "\n",
    "Let\\'s start by reimplementing the code above using\n",
    "`torch.nn.utils.parametrize`. The only thing that we have to do is to\n",
    "write the parametrization as a regular `nn.Module`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Symmetric(nn.Module):\n",
    "    def forward(self, X):\n",
    "        return X.triu() + X.triu(1).transpose(-1, -2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is all we need to do. Once we have this, we can transform any\n",
    "regular layer into a symmetric layer by doing\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer, \"weight\", Symmetric())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, the matrix of the linear layer is symmetric\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "A = layer.weight\n",
    "assert torch.allclose(A, A.T)  # A is symmetric\n",
    "print(A)                       # Quick visual check"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can do the same thing with any other layer. For example, we can\n",
    "create a CNN with\n",
    "[skew-symmetric](https://en.wikipedia.org/wiki/Skew-symmetric_matrix)\n",
    "kernels. We use a similar parametrization, copying the upper-triangular\n",
    "part with signs reversed into the lower-triangular part\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Skew(nn.Module):\n",
    "    def forward(self, X):\n",
    "        A = X.triu(1)\n",
    "        return A - A.transpose(-1, -2)\n",
    "\n",
    "\n",
    "cnn = nn.Conv2d(in_channels=5, out_channels=8, kernel_size=3)\n",
    "parametrize.register_parametrization(cnn, \"weight\", Skew())\n",
    "# Print a few kernels\n",
    "print(cnn.weight[0, 1])\n",
    "print(cnn.weight[2, 2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inspecting a parametrized module\n",
    "\n",
    "When a module is parametrized, we find that the module has changed in\n",
    "three ways:\n",
    "\n",
    "1)  `model.weight` is now a property\n",
    "2)  It has a new `module.parametrizations` attribute\n",
    "3)  The unparametrized weight has been moved to\n",
    "    `module.parametrizations.weight.original`\n",
    "\n",
    "| \n",
    "\n",
    "After parametrizing `weight`, `layer.weight` is turned into a [Python\n",
    "property](https://docs.python.org/3/library/functions.html#property).\n",
    "This property computes `parametrization(weight)` every time we request\n",
    "`layer.weight` just as we did in our implementation of `LinearSymmetric`\n",
    "above.\n",
    "\n",
    "Registered parametrizations are stored under a `parametrizations`\n",
    "attribute within the module.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 3)\n",
    "print(f\"Unparametrized:\\n{layer}\")\n",
    "parametrize.register_parametrization(layer, \"weight\", Symmetric())\n",
    "print(f\"\\nParametrized:\\n{layer}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This `parametrizations` attribute is an `nn.ModuleDict`, and it can be\n",
    "accessed as such\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(layer.parametrizations)\n",
    "print(layer.parametrizations.weight)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each element of this `nn.ModuleDict` is a `ParametrizationList`, which\n",
    "behaves like an `nn.Sequential`. This list will allow us to concatenate\n",
    "parametrizations on one weight. Since this is a list, we can access the\n",
    "parametrizations indexing it. Here\\'s where our `Symmetric`\n",
    "parametrization sits\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(layer.parametrizations.weight[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The other thing that we notice is that, if we print the parameters, we\n",
    "see that the parameter `weight` has been moved\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(dict(layer.named_parameters()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It now sits under `layer.parametrizations.weight.original`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(layer.parametrizations.weight.original)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Besides these three small differences, the parametrization is doing\n",
    "exactly the same as our manual implementation\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "symmetric = Symmetric()\n",
    "weight_orig = layer.parametrizations.weight.original\n",
    "print(torch.dist(layer.weight, symmetric(weight_orig)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parametrizations are first-class citizens\n",
    "\n",
    "Since `layer.parametrizations` is an `nn.ModuleList`, it means that the\n",
    "parametrizations are properly registered as submodules of the original\n",
    "module. As such, the same rules for registering parameters in a module\n",
    "apply to register a parametrization. For example, if a parametrization\n",
    "has parameters, these will be moved from CPU to CUDA when calling\n",
    "`model = model.cuda()`.\n",
    "\n",
    "# Caching the value of a parametrization\n",
    "\n",
    "Parametrizations come with an inbuilt caching system via the context\n",
    "manager `parametrize.cached()`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class NoisyParametrization(nn.Module):\n",
    "    def forward(self, X):\n",
    "        print(\"Computing the Parametrization\")\n",
    "        return X\n",
    "\n",
    "layer = nn.Linear(4, 4)\n",
    "parametrize.register_parametrization(layer, \"weight\", NoisyParametrization())\n",
    "print(\"Here, layer.weight is recomputed every time we call it\")\n",
    "foo = layer.weight + layer.weight.T\n",
    "bar = layer.weight.sum()\n",
    "with parametrize.cached():\n",
    "    print(\"Here, it is computed just the first time layer.weight is called\")\n",
    "    foo = layer.weight + layer.weight.T\n",
    "    bar = layer.weight.sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Concatenating parametrizations\n",
    "\n",
    "Concatenating two parametrizations is as easy as registering them on the\n",
    "same tensor. We may use this to create more complex parametrizations\n",
    "from simpler ones. For example, the [Cayley\n",
    "map](https://en.wikipedia.org/wiki/Cayley_transform#Matrix_map) maps the\n",
    "skew-symmetric matrices to the orthogonal matrices of positive\n",
    "determinant. We can concatenate `Skew` and a parametrization that\n",
    "implements the Cayley map to get a layer with orthogonal weights\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class CayleyMap(nn.Module):\n",
    "    def __init__(self, n):\n",
    "        super().__init__()\n",
    "        self.register_buffer(\"Id\", torch.eye(n))\n",
    "\n",
    "    def forward(self, X):\n",
    "        # (I + X)(I - X)^{-1}\n",
    "        return torch.linalg.solve(self.Id - X, self.Id + X)\n",
    "\n",
    "layer = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer, \"weight\", Skew())\n",
    "parametrize.register_parametrization(layer, \"weight\", CayleyMap(3))\n",
    "X = layer.weight\n",
    "print(torch.dist(X.T @ X, torch.eye(3)))  # X is orthogonal"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This may also be used to prune a parametrized module, or to reuse\n",
    "parametrizations. For example, the matrix exponential maps the symmetric\n",
    "matrices to the Symmetric Positive Definite (SPD) matrices But the\n",
    "matrix exponential also maps the skew-symmetric matrices to the\n",
    "orthogonal matrices. Using these two facts, we may reuse the\n",
    "parametrizations before to our advantage\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class MatrixExponential(nn.Module):\n",
    "    def forward(self, X):\n",
    "        return torch.matrix_exp(X)\n",
    "\n",
    "layer_orthogonal = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer_orthogonal, \"weight\", Skew())\n",
    "parametrize.register_parametrization(layer_orthogonal, \"weight\", MatrixExponential())\n",
    "X = layer_orthogonal.weight\n",
    "print(torch.dist(X.T @ X, torch.eye(3)))         # X is orthogonal\n",
    "\n",
    "layer_spd = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer_spd, \"weight\", Symmetric())\n",
    "parametrize.register_parametrization(layer_spd, \"weight\", MatrixExponential())\n",
    "X = layer_spd.weight\n",
    "print(torch.dist(X, X.T))                        # X is symmetric\n",
    "print((torch.linalg.eigvalsh(X) > 0.).all())  # X is positive definite"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Initializing parametrizations\n",
    "\n",
    "Parametrizations come with a mechanism to initialize them. If we\n",
    "implement a method `right_inverse` with signature\n",
    "\n",
    "``` python\n",
    "def right_inverse(self, X: Tensor) -> Tensor\n",
    "```\n",
    "\n",
    "it will be used when assigning to the parametrized tensor.\n",
    "\n",
    "Let\\'s upgrade our implementation of the `Skew` class to support this\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Skew(nn.Module):\n",
    "    def forward(self, X):\n",
    "        A = X.triu(1)\n",
    "        return A - A.transpose(-1, -2)\n",
    "\n",
    "    def right_inverse(self, A):\n",
    "        # We assume that A is skew-symmetric\n",
    "        # We take the upper-triangular elements, as these are those used in the forward\n",
    "        return A.triu(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We may now initialize a layer that is parametrized with `Skew`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer, \"weight\", Skew())\n",
    "X = torch.rand(3, 3)\n",
    "X = X - X.T                             # X is now skew-symmetric\n",
    "layer.weight = X                        # Initialize layer.weight to be X\n",
    "print(torch.dist(layer.weight, X))      # layer.weight == X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This `right_inverse` works as expected when we concatenate\n",
    "parametrizations. To see this, let\\'s upgrade the Cayley parametrization\n",
    "to also support being initialized\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class CayleyMap(nn.Module):\n",
    "    def __init__(self, n):\n",
    "        super().__init__()\n",
    "        self.register_buffer(\"Id\", torch.eye(n))\n",
    "\n",
    "    def forward(self, X):\n",
    "        # Assume X skew-symmetric\n",
    "        # (I + X)(I - X)^{-1}\n",
    "        return torch.linalg.solve(self.Id - X, self.Id + X)\n",
    "\n",
    "    def right_inverse(self, A):\n",
    "        # Assume A orthogonal\n",
    "        # See https://en.wikipedia.org/wiki/Cayley_transform#Matrix_map\n",
    "        # (A - I)(A + I)^{-1}\n",
    "        return torch.linalg.solve(A + self.Id, self.Id - A)\n",
    "\n",
    "layer_orthogonal = nn.Linear(3, 3)\n",
    "parametrize.register_parametrization(layer_orthogonal, \"weight\", Skew())\n",
    "parametrize.register_parametrization(layer_orthogonal, \"weight\", CayleyMap(3))\n",
    "# Sample an orthogonal matrix with positive determinant\n",
    "X = torch.empty(3, 3)\n",
    "nn.init.orthogonal_(X)\n",
    "if X.det() < 0.:\n",
    "    X[0].neg_()\n",
    "layer_orthogonal.weight = X\n",
    "print(torch.dist(layer_orthogonal.weight, X))  # layer_orthogonal.weight == X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This initialization step can be written more succinctly by sampling\n",
    "straight into `layer_orthogonal.weight`. The determinant correction is\n",
    "still needed: `nn.init.orthogonal_` samples from `O(3)`, and when\n",
    "`det(A) = -1` the matrix has an eigenvalue at `-1`, which makes the\n",
    "`A + I` that `CayleyMap.right_inverse` inverts singular.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "X = nn.init.orthogonal_(layer_orthogonal.weight)\n",
    "if X.det() < 0.:\n",
    "    X[0].neg_()\n",
    "layer_orthogonal.weight = X"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The name of this method comes from the fact that we would often expect\n",
    "that `forward(right_inverse(X)) == X`. This is a direct way of rewriting\n",
    "that the forward after the initialization with value `X` should return\n",
    "the value `X`. This constraint is not strongly enforced in practice. In\n",
    "fact, at times, it might be of interest to relax this relation. For\n",
    "example, consider the following implementation of a randomized pruning\n",
    "method:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class PruningParametrization(nn.Module):\n",
    "    def __init__(self, X, p_drop=0.2):\n",
    "        super().__init__()\n",
    "        # sample zeros with probability p_drop\n",
    "        mask = torch.full_like(X, 1.0 - p_drop)\n",
    "        self.mask = torch.bernoulli(mask)\n",
    "\n",
    "    def forward(self, X):\n",
    "        return X * self.mask\n",
    "\n",
    "    def right_inverse(self, A):\n",
    "        return A"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, it is not true that for every matrix A\n",
    "`forward(right_inverse(A)) == A`. This is only true when the matrix `A`\n",
    "has zeros in the same positions as the mask. Even then, if we assign a\n",
    "tensor to a pruned parameter, it will comes as no surprise that tensor\n",
    "will be, in fact, pruned\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 4)\n",
    "X = torch.rand_like(layer.weight)\n",
    "print(f\"Initialization matrix:\\n{X}\")\n",
    "parametrize.register_parametrization(layer, \"weight\", PruningParametrization(layer.weight))\n",
    "layer.weight = X\n",
    "print(f\"\\nInitialized weight:\\n{layer.weight}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Removing parametrizations\n",
    "\n",
    "We may remove all the parametrizations from a parameter or a buffer in a\n",
    "module by using `parametrize.remove_parametrizations()`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 3)\n",
    "print(\"Before:\")\n",
    "print(layer)\n",
    "print(layer.weight)\n",
    "parametrize.register_parametrization(layer, \"weight\", Skew())\n",
    "print(\"\\nParametrized:\")\n",
    "print(layer)\n",
    "print(layer.weight)\n",
    "parametrize.remove_parametrizations(layer, \"weight\")\n",
    "print(\"\\nAfter. Weight has skew-symmetric values but it is unconstrained:\")\n",
    "print(layer)\n",
    "print(layer.weight)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When removing a parametrization, we may choose to leave the original\n",
    "parameter (i.e. that in `layer.parametriations.weight.original`) rather\n",
    "than its parametrized version by setting the flag\n",
    "`leave_parametrized=False`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "layer = nn.Linear(3, 3)\n",
    "print(\"Before:\")\n",
    "print(layer)\n",
    "print(layer.weight)\n",
    "parametrize.register_parametrization(layer, \"weight\", Skew())\n",
    "print(\"\\nParametrized:\")\n",
    "print(layer)\n",
    "print(layer.weight)\n",
    "parametrize.remove_parametrizations(layer, \"weight\", leave_parametrized=False)\n",
    "print(\"\\nAfter. Same as Before:\")\n",
    "print(layer)\n",
    "print(layer.weight)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
