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

class SoftSignSGD(Optimizer):
    def __init__(self, params, lr=1e-3, betas=[0.9, 0.999], eps=1e-8,
                 weight_decay=0, power=2.0, amsgrad=False, nesterov=True):
        
        print("SoftSignSGD_V3")
        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, power=power, amsgrad=amsgrad, nesterov=nesterov)
        super(SoftSignSGD, self).__init__(params, defaults)

    def __setstate__(self, state):
        super(SoftSignSGD, 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')
                amsgrad = group['amsgrad']
                nesterov = group['nesterov']
                p.mul_(1 - group['lr'] * group['weight_decay'])
                state = self.state[p]

                power = group['power']
                
                # State initialization
                if len(state) == 0:
                    # Exponential moving average of gradient values
                    state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format).float()
                    # Exponential moving average of squared gradient values
                    state['exp_avg_abs'] = torch.zeros_like(p, memory_format=torch.preserve_format).float()
                    

                    
               
                exp_avg, exp_avg_abs = state['exp_avg'], state['exp_avg_abs']
                beta1, beta2 = group['betas']


                exp_avg.mul_(beta1).add_(grad, alpha=1-beta1)
                exp_avg_abs.mul_(beta1).add_((grad.abs())**power, alpha=1-beta1)
                
                if nesterov:
                    numerator = (1-beta1)*grad + beta1*exp_avg
                    denominator = ((1-beta1)*(grad.abs())**power + beta1*exp_avg_abs)**(1/power)
                    multi = numerator / denominator.add_(group['eps'])
                else:
                    multi = exp_avg / (exp_avg_abs**(1/power)).add_(group['eps'])

                step_size = group['lr']
                p.add_(multi, alpha=-step_size)

        return loss