File size: 10,036 Bytes
ad63418 | 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | import torch
from torch.optim import Optimizer
import math
class CustomAdamW(Optimizer):
def __init__(self, params, lr = 1e-3, betas = (0.9, 0.95), eps = 1e-8, weight_decay = 0.1):
defaults = dict(lr = lr, betas = betas, eps = eps, weight_decay = weight_decay)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure = None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group["lr"]
beta1, beta2 = group["betas"]
eps = group["eps"]
weight_decay = group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad
if grad.is_sparse:
raise RuntimeError("CustomAdamW does not support sparse gradients")
state = self.state[p]
if len(state) == 0:
state["step"] = 0
if "m" not in state:
state["m"] = torch.zeros_like(p.data)
if "v" not in state:
state["v"] = torch.zeros_like(p.data)
state["step"] += 1
step = state["step"]
## Moment Updation
state["m"] = beta1 * state["m"] + (1 - beta1) * grad
state["v"] = beta2 * state["v"] + (1 - beta2) * (grad ** 2)
## Bias Correction
bias_correction1 = 1.0 - beta1 ** step
m_hat = state["m"] / bias_correction1
bias_correction2 = 1.0 - beta2 ** step
v_hat = state["v"] / bias_correction2
## Weight Update
p.data = p.data - lr * m_hat / (torch.sqrt(v_hat) + eps) - lr * p.data * weight_decay
return loss
class CustomCautious(Optimizer):
def __init__(self, params, lr = 1e-3, betas = (0.9, 0.95), eps = 1e-8, weight_decay = 0.1):
defaults = dict(lr = lr, betas = betas, eps = eps, weight_decay = weight_decay)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure = None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group["lr"]
beta1, beta2 = group["betas"]
eps = group["eps"]
weight_decay = group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad
if grad.is_sparse:
raise RuntimeError("CustomAdamW does not support sparse gradients")
state = self.state[p]
if len(state) == 0:
state["step"] = 0
if "m" not in state:
state["m"] = torch.zeros_like(p.data)
if "v" not in state:
state["v"] = torch.zeros_like(p.data)
state["step"] += 1
step = state["step"]
## Moment Updation
state["m"] = beta1 * state["m"] + (1 - beta1) * grad
state["v"] = beta2 * state["v"] + (1 - beta2) * (grad ** 2)
## Bias Correction
bias_correction1 = 1.0 - beta1 ** step
m_hat = state["m"] / bias_correction1
bias_correction2 = 1.0 - beta2 ** step
v_hat = state["v"] / bias_correction2
## Calculate u
u = m_hat / (torch.sqrt(v_hat) + eps)
## Calculate s
s = (u * grad > 0).float()
## Calculate u_hat
u_hat = (u * s) / torch.clamp(torch.mean(s), min = 1e-8)
## Weight Update
p.data = p.data - lr * u_hat - lr * weight_decay * p.data
return loss
class CustomLion(Optimizer):
def __init__(self, params, lr = 2e-4, betas = (0.9, 0.99), weight_decay = 0.5):
defaults = dict(lr = lr, betas = betas, weight_decay = weight_decay)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure = None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group["lr"]
beta1, beta2 = group["betas"]
weight_decay = group["weight_decay"]
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad
if grad.is_sparse:
raise RuntimeError("CustomAdamW does not support sparse gradients")
state = self.state[p]
if len(state) == 0:
state["step"] = 0
if "m" not in state:
state["m"] = torch.zeros_like(p.data)
state["step"] += 1
## Calculate m_hat
m_hat = beta1 * state["m"] + (1 - beta1) * grad
## Moment Updation
state["m"] = beta2 * state["m"] + (1 - beta2) * grad
## Weight update
p.data = p.data - lr * torch.sign(m_hat) - lr * weight_decay * p.data
return loss
def newtonschulz_orthogonalization(X, steps = 5, eps = 1e-7):
if X.ndim != 2:
raise ValueError(f"expected 2D matrix, but got a tensor with {X.ndim} dimensions")
rows, cols = X.shape
is_transposed = False
if rows > cols:
X = X.T
is_transposed = True
norm = torch.linalg.matrix_norm(X)
X = X / (norm + eps)
a, b, c = (3.4445, -4.7750, 2.0315)
for _ in range(1, steps + 1):
first_term = a * X
A = X @ X.T
second_term = ((b * A) + c * (A @ A)) @ X
X = first_term + second_term
if is_transposed:
X = X.T
return X
class CustomScion(Optimizer):
def __init__(self, params, lr = 1e-3, beta = 0.9, weight_decay = 0.01, steps = 5, eps = 1e-7):
defaults = dict(lr = lr, beta = beta, weight_decay = weight_decay, steps = steps, eps = eps)
super().__init__(params, defaults)
@torch.no_grad()
def step(self, closure = None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group["lr"]
beta = group["beta"]
weight_decay = group["weight_decay"]
steps = group["steps"]
eps = group["eps"]
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad
if grad.is_sparse:
raise RuntimeError("CustomScion does not support sparse gradients")
state = self.state[p]
if len(state) == 0:
state["step"] = 0
if "m" not in state:
state["m"] = torch.zeros_like(p.data)
state["step"] += 1
## Momentum update
state["m"] = beta * state["m"] + grad
## Calculate u
u = beta * state["m"] + grad
## Apply NewtonSchulz Orthogonalization
if p.ndim == 2:
u = newtonschulz_orthogonalization(u, steps = steps, eps = eps)
rows, cols = p.data.shape
s = math.sqrt(max(1, rows / cols))
u = u * s
else:
u = torch.sign(u)
## Weight update
p.data = p.data - lr * u - lr * weight_decay * p.data
return loss
class CustomSophia(Optimizer):
def __init__(self, params, lr = 1e-4, betas = (0.965, 0.99), rho = 0.04, weight_decay = 0.1, eps = 1e-12):
defaults = dict(lr = lr, betas = betas, rho = rho, weight_decay = weight_decay, eps = eps)
super().__init__(params, defaults)
@torch.no_grad()
def update_hessian(self):
for group in self.param_groups:
beta1, beta2 = group["betas"]
for p in group["params"]:
if p.grad is None:
continue
state = self.state[p]
grad = p.grad
if "h" not in state:
state["h"] = torch.zeros_like(p.data)
state["h"] = beta2 * state["h"] + (1 - beta2) * (grad ** 2)
@torch.no_grad()
def step(self, closure = None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group["lr"]
beta1, beta2 = group["betas"]
rho = group["rho"]
weight_decay = group["weight_decay"]
eps = group["eps"]
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad
if grad.is_sparse:
raise RuntimeError("CustomSophia does not support sparse gradients")
state = self.state[p]
if "step" not in state:
state["step"] = 0
if "m" not in state:
state["m"] = torch.zeros_like(p.data)
if "h" not in state:
state["h"] = torch.zeros_like(p.data)
state["step"] += 1
state["m"] = beta1 * state["m"] + (1 - beta1) * grad
denom = torch.clamp(rho * state["h"], min = eps)
ratio = torch.clamp(state["m"] / denom, min = -1.0, max = 1.0)
p.data = p.data - lr * ratio - lr * weight_decay * p.data
return loss
|