Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss.
(self, closure=None)
| 73 | return True |
| 74 | |
| 75 | def step(self, closure=None): |
| 76 | """Performs a single optimization step. |
| 77 | |
| 78 | Args: |
| 79 | closure (callable, optional): A closure that reevaluates the model |
| 80 | and returns the loss. |
| 81 | """ |
| 82 | loss = None |
| 83 | if closure is not None: |
| 84 | loss = closure() |
| 85 | |
| 86 | for group in self.param_groups: |
| 87 | for p in group["params"]: |
| 88 | if p.grad is None: |
| 89 | continue |
| 90 | grad = p.grad.data |
| 91 | if grad.dtype in {torch.float16, torch.bfloat16}: |
| 92 | grad = grad.float() |
| 93 | if grad.is_sparse: |
| 94 | raise RuntimeError( |
| 95 | "Adam does not support sparse gradients, please consider SparseAdam instead" |
| 96 | ) |
| 97 | amsgrad = group.get("amsgrad", False) |
| 98 | |
| 99 | p_data_fp32 = p.data |
| 100 | if p.data.dtype in {torch.float16, torch.bfloat16}: |
| 101 | p_data_fp32 = p_data_fp32.float() |
| 102 | |
| 103 | state = self.state[p] |
| 104 | |
| 105 | # State initialization |
| 106 | if len(state) == 0: |
| 107 | state["step"] = 0 |
| 108 | # Exponential moving average of gradient values |
| 109 | state["exp_avg"] = torch.zeros_like(p_data_fp32) |
| 110 | # Exponential moving average of squared gradient values |
| 111 | state["exp_avg_sq"] = torch.zeros_like(p_data_fp32) |
| 112 | if amsgrad: |
| 113 | # Maintains max of all exp. moving avg. of sq. grad. values |
| 114 | state["max_exp_avg_sq"] = torch.zeros_like(p_data_fp32) |
| 115 | else: |
| 116 | state["exp_avg"] = state["exp_avg"].to(p_data_fp32) |
| 117 | state["exp_avg_sq"] = state["exp_avg_sq"].to(p_data_fp32) |
| 118 | if amsgrad: |
| 119 | state["max_exp_avg_sq"] = state["max_exp_avg_sq"].to(p_data_fp32) |
| 120 | |
| 121 | exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] |
| 122 | if amsgrad: |
| 123 | max_exp_avg_sq = state["max_exp_avg_sq"] |
| 124 | beta1, beta2 = group["betas"] |
| 125 | |
| 126 | state["step"] += 1 |
| 127 | |
| 128 | # Decay the first and second moment running average coefficient |
| 129 | exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1) |
| 130 | exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2) |
| 131 | if amsgrad: |
| 132 | # Maintains the maximum of all 2nd moment running avg. till now |
no outgoing calls
no test coverage detected