-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrsgd.py
30 lines (24 loc) · 879 Bytes
/
rsgd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from typing import Iterator
import torch
from torch import nn
from torch.optim.optimizer import required
from manifold import Manifold
class RSGD(torch.optim.SGD):
'''
Implements Riemannian Stochastic Gradient Descent.
'''
def __init__(self,
params: Iterator[nn.Parameter],
manifold: Manifold,
lr=required):
super().__init__(params, lr)
self.manifold = manifold
def step(self):
with torch.no_grad():
for group in self.param_groups:
lr = group["lr"]
for p in group["params"]:
if p.grad is None:
continue
lambda_square = self.manifold.conformal_factor(p, keepdim=True) ** 2
p.data.copy_(self.manifold.exp(p, -lr * p.grad.data / lambda_square))