Skip to content

Commit 72e11e5

Browse files
committed
Repair parametrization notebook examples
1 parent a0c03a5 commit 72e11e5

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

‎examples/parametrisations.ipynb‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@
6767
"outputs": [],
6868
"source": [
6969
"class SymmetricParametrization(nn.Module):\n",
70-
" def forward(X):\n",
70+
" def forward(self, X):\n",
7171
" A = X.triu()\n",
7272
" return A + A.T "
7373
]
@@ -113,9 +113,10 @@
113113
"source": [
114114
"class PruningParametrization(nn.Module):\n",
115115
" def __init__(self, X, p_drop=0.2):\n",
116+
" super().__init__()\n",
116117
" # sample zeros with probability p_drop\n",
117118
" mask = torch.full_like(X, 1.0 - p_drop)\n",
118-
" self.mask = torch.bernoulli(mask)\n",
119+
" self.register_buffer(\"mask\", torch.bernoulli(mask))\n",
119120
"\n",
120121
" def forward(self, X):\n",
121122
" return X * self.mask"
@@ -322,6 +323,8 @@
322323
"# In other words, right_inverse is a right inverse of forward.\n",
323324
"\n",
324325
"model = nn.Linear(5, 5)\n",
326+
"with torch.no_grad():\n",
327+
" model.weight.copy_(model.weight - model.weight.T)\n",
325328
"P.register_parametrization(model, \"weight\", Skew())\n",
326329
"# Just computes `model.weight` once\n",
327330
"with P.cached():\n",
@@ -347,11 +350,11 @@
347350
" def forward(self, A):\n",
348351
" # Cayley map: (I + A)(I - A)^{-1}\n",
349352
" # This is orthogonal whenever A is skew-symmetric\n",
350-
" Id = torch.eye(A.size(0))\n",
353+
" Id = torch.eye(A.size(0), dtype=A.dtype, device=A.device)\n",
351354
" return self.B @ torch.linalg.solve(Id - A, Id + A)\n",
352355
"\n",
353356
" def is_orthogonal(self, X):\n",
354-
" Id = torch.eye(X.size(0))\n",
357+
" Id = torch.eye(X.size(0), dtype=X.dtype, device=X.device)\n",
355358
" return torch.allclose(X.T @ X, Id, atol=1e-6)\n",
356359
"\n",
357360
" def right_inverse(self, X):\n",
@@ -362,9 +365,14 @@
362365
" return torch.zeros_like(X)\n",
363366
"\n",
364367
"\n",
365-
"model = nn.Linear(5,5)\n",
368+
"model = nn.Linear(4, 4)\n",
369+
"X = torch.zeros_like(model.weight)\n",
370+
"X.diagonal(offset=1)[::2] = 1.0\n",
371+
"X = X - X.T\n",
372+
"with torch.no_grad():\n",
373+
" model.weight.copy_(X)\n",
366374
"P.register_parametrization(model, \"weight\", Skew())\n",
367-
"P.register_parametrization(model, \"weight\", Orthogonal(5))\n",
375+
"P.register_parametrization(model, \"weight\", Orthogonal(4))\n",
368376
"\n",
369377
"# Sample an orthogonal matrix and initialise the layer\n",
370378
"X = torch.empty_like(model.weight)\n",

0 commit comments

Comments
 (0)