import math
import torch
import logging
from torch.optim.optimizer import Optimizer, required

class Lion(Optimizer):
    def __init__(self, params, lr=1e-3, betas=[0.9, 0.999], eps=1e-8,
                 weight_decay=0):
        
        if not 0.0 <= lr:
            raise ValueError("Invalid learning rate: {}".format(lr))
        if not 0.0 <= eps:
            raise ValueError("Invalid epsilon value: {}".format(eps))
        if not 0.0 <= betas[0] <= 1.0:
            raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0]))
        if not 0.0 <= betas[1] <= 1.0:
            raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1]))
        if not 0.0 <= weight_decay:
            raise ValueError("Invalid weight_decay value: {}".format(weight_decay))
        defaults = dict(lr=lr, betas=betas, eps=eps,
                        weight_decay=weight_decay)
        super(Lion, self).__init__(params, defaults)

    def __setstate__(self, state):
        super(Lion, self).__setstate__(state)
        for group in self.param_groups:
            group.setdefault('amsgrad', False)
    
    @torch.no_grad()
    def step(self, closure=None):
        """Performs a single optimization step.

        Arguments:
            closure (callable, optional): A closure that reevaluates the model
                and returns the loss.
        """
        loss = None
        if closure is not None:
            with torch.enable_grad():
                loss = closure()

        for group in self.param_groups:
            for p in group['params']:
                if p.grad is None:
                    continue
                grad = p.grad
                if grad.is_sparse:
                    raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')
                p.mul_(1 - group['lr'] * group['weight_decay'])
                state = self.state[p]
                
                # State initialization
                if len(state) == 0:
                    # Exponential moving average of gradient values
                    state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format)
                    # Exponential moving average of squared gradient values
                    

                exp_avg = state['exp_avg']
                beta1, beta2 = group['betas']
                
                #exp_avg.mul_(beta2).add_(grad, alpha=1-beta2)
                #p.add_(exp_avg.sign(), alpha=-group['lr'])
                multi = beta1 * exp_avg + (1- beta1) * grad
                p.add_(multi.sign(), alpha=-group['lr'])
                exp_avg.mul_(beta2).add_(grad, alpha=1-beta2)
                


        return loss