|
| 1 | +import math |
| 2 | +import torch |
| 3 | +from transformers import Adafactor |
| 4 | + |
| 5 | +@torch.no_grad() |
| 6 | +def adafactor_step_param(self, p, group): |
| 7 | + if p.grad is None: |
| 8 | + return |
| 9 | + grad = p.grad |
| 10 | + if grad.dtype in {torch.float16, torch.bfloat16}: |
| 11 | + grad = grad.float() |
| 12 | + if grad.is_sparse: |
| 13 | + raise RuntimeError("Adafactor does not support sparse gradients.") |
| 14 | + |
| 15 | + state = self.state[p] |
| 16 | + grad_shape = grad.shape |
| 17 | + |
| 18 | + factored, use_first_moment = Adafactor._get_options(group, grad_shape) |
| 19 | + # State Initialization |
| 20 | + if len(state) == 0: |
| 21 | + state["step"] = 0 |
| 22 | + |
| 23 | + if use_first_moment: |
| 24 | + # Exponential moving average of gradient values |
| 25 | + state["exp_avg"] = torch.zeros_like(grad) |
| 26 | + if factored: |
| 27 | + state["exp_avg_sq_row"] = torch.zeros(grad_shape[:-1]).to(grad) |
| 28 | + state["exp_avg_sq_col"] = torch.zeros(grad_shape[:-2] + grad_shape[-1:]).to(grad) |
| 29 | + else: |
| 30 | + state["exp_avg_sq"] = torch.zeros_like(grad) |
| 31 | + |
| 32 | + state["RMS"] = 0 |
| 33 | + else: |
| 34 | + if use_first_moment: |
| 35 | + state["exp_avg"] = state["exp_avg"].to(grad) |
| 36 | + if factored: |
| 37 | + state["exp_avg_sq_row"] = state["exp_avg_sq_row"].to(grad) |
| 38 | + state["exp_avg_sq_col"] = state["exp_avg_sq_col"].to(grad) |
| 39 | + else: |
| 40 | + state["exp_avg_sq"] = state["exp_avg_sq"].to(grad) |
| 41 | + |
| 42 | + p_data_fp32 = p |
| 43 | + if p.dtype in {torch.float16, torch.bfloat16}: |
| 44 | + p_data_fp32 = p_data_fp32.float() |
| 45 | + |
| 46 | + state["step"] += 1 |
| 47 | + state["RMS"] = Adafactor._rms(p_data_fp32) |
| 48 | + lr = Adafactor._get_lr(group, state) |
| 49 | + |
| 50 | + beta2t = 1.0 - math.pow(state["step"], group["decay_rate"]) |
| 51 | + update = (grad ** 2) + group["eps"][0] |
| 52 | + if factored: |
| 53 | + exp_avg_sq_row = state["exp_avg_sq_row"] |
| 54 | + exp_avg_sq_col = state["exp_avg_sq_col"] |
| 55 | + |
| 56 | + exp_avg_sq_row.mul_(beta2t).add_(update.mean(dim=-1), alpha=(1.0 - beta2t)) |
| 57 | + exp_avg_sq_col.mul_(beta2t).add_(update.mean(dim=-2), alpha=(1.0 - beta2t)) |
| 58 | + |
| 59 | + # Approximation of exponential moving average of square of gradient |
| 60 | + update = Adafactor._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col) |
| 61 | + update.mul_(grad) |
| 62 | + else: |
| 63 | + exp_avg_sq = state["exp_avg_sq"] |
| 64 | + |
| 65 | + exp_avg_sq.mul_(beta2t).add_(update, alpha=(1.0 - beta2t)) |
| 66 | + update = exp_avg_sq.rsqrt().mul_(grad) |
| 67 | + |
| 68 | + update.div_((Adafactor._rms(update) / group["clip_threshold"]).clamp_(min=1.0)) |
| 69 | + update.mul_(lr) |
| 70 | + |
| 71 | + if use_first_moment: |
| 72 | + exp_avg = state["exp_avg"] |
| 73 | + exp_avg.mul_(group["beta1"]).add_(update, alpha=(1 - group["beta1"])) |
| 74 | + update = exp_avg |
| 75 | + |
| 76 | + if group["weight_decay"] != 0: |
| 77 | + p_data_fp32.add_(p_data_fp32, alpha=(-group["weight_decay"] * lr)) |
| 78 | + |
| 79 | + p_data_fp32.add_(-update) |
| 80 | + |
| 81 | + if p.dtype in {torch.float16, torch.bfloat16}: |
| 82 | + p.copy_(p_data_fp32) |
| 83 | + |
| 84 | + |
| 85 | +@torch.no_grad() |
| 86 | +def adafactor_step(self, closure=None): |
| 87 | + """ |
| 88 | + Performs a single optimization step |
| 89 | +
|
| 90 | + Arguments: |
| 91 | + closure (callable, optional): A closure that reevaluates the model |
| 92 | + and returns the loss. |
| 93 | + """ |
| 94 | + loss = None |
| 95 | + if closure is not None: |
| 96 | + loss = closure() |
| 97 | + |
| 98 | + for group in self.param_groups: |
| 99 | + for p in group["params"]: |
| 100 | + adafactor_step_param(self, p, group) |
| 101 | + |
| 102 | + return loss |
| 103 | + |
| 104 | +def patch_adafactor_fused(optimizer: Adafactor): |
| 105 | + optimizer.step_param = adafactor_step_param.__get__(optimizer) |
| 106 | + optimizer.step = adafactor_step.__get__(optimizer) |
0 commit comments