import math
import torch
from torch.optim import Optimizer

class AdamExponent(Optimizer):
    r"""Implements Adam, but uses (v + eps)^exponent instead of sqrt(v + eps).

    Arguments:
        params (iterable): iterable of parameters to optimize
        lr (float): learning rate
        betas (Tuple[float, float]): coefficients used for computing
            running averages of gradient and its square (default: (0.9, 0.999))
        eps (float): term added to the denominator to improve numerical stability (default: 1e-8)
        exponent (float): the exponent to use in the denominator (default: 0.5)
        weight_decay (float): weight decay (L2 penalty) (default: 0)
        correct_bias (bool): whether to apply bias correction (default: True)
    """

    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,
                 exponent=0.5, weight_decay=0, correct_bias=True):
        defaults = dict(lr=lr, betas=betas, eps=eps,
                        exponent=exponent,
                        weight_decay=weight_decay,
                        correct_bias=correct_bias)
        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:
            beta1, beta2 = group['betas']
            exp = group['exponent']
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad

                state = self.state[p]
                # State initialization
                if not state:
                    state['step'] = 0
                    state['exp_avg'] = torch.zeros_like(p)
                    state['exp_avg_sq'] = torch.zeros_like(p)

                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']
                state['step'] += 1
                step = state['step']

                if group['weight_decay'] != 0:
                    grad = grad.add(p, alpha=group['weight_decay'])

                # Decay the first and second moment running average coefficient
                exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
                exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)

                if group['correct_bias']:
                    bias_correction1 = 1 - beta1 ** step
                    bias_correction2 = 1 - beta2 ** step
                    # bias‐corrected moments
                    m_hat = exp_avg / bias_correction1
                    v_hat = exp_avg_sq / bias_correction2
                else:
                    m_hat = exp_avg
                    v_hat = exp_avg_sq

                # HERE is the only change from Adam: arbitrary exponent
                denom = v_hat.pow(group['exponent']).add_(group['eps'])

                p.addcdiv_(m_hat, denom, value=-group['lr'])

        return loss
