import math
import os

class OptimizerParamScheduler(object):
    """Anneals learning rate and weight decay"""

    def __init__(self, args, optimizer):
        # Class values.
        self.rank = int(os.environ.get("RANK", default='0'))
        self.args = args
        self.optimizer = optimizer
        self.num_steps = 0

        self.begin_lr = float(args.lr_begin)
        self.lr_decay_factor = float(args.lr_decay_factor)
        self.max_lr = float(args.lr_max)
        self.min_lr = self.max_lr/self.lr_decay_factor
        assert self.lr_decay_factor > 1.0
        assert 0.0 <= self.min_lr <= self.max_lr

        total_step = args.batch_num * args.train_iters
        self.lr_warmup_steps = int(total_step * args.lr_warmup_ratio)
        self.lr_decay_steps = int(total_step * args.lr_decay_ratio)
        assert self.lr_decay_steps > 0
        assert self.lr_warmup_steps < self.lr_decay_steps
        assert self.lr_warmup_steps + self.lr_decay_steps <= total_step

        self.lr_decay_style = args.lr_decay_style
        self.start_wd = args.start_weight_decay
        self.end_wd = args.end_weight_decay
        assert 0.0 <= self.start_wd <= self.end_wd
        self.wd_incr_steps = total_step
        self.wd_incr_style = args.weight_decay_incr_style

        self.start_grad_accum = args.start_grad_accum
        self.end_grad_accum = args.end_grad_accum
        assert 1.0 <= self.start_grad_accum <= self.end_grad_accum
        self.grad_incr_steps = total_step
        self.grad_accum_step_incr_style = args.grad_accum_step_incr_style

        self.override_opt_param_scheduler = args.override_opt_param_scheduler
        self.use_checkpoint_opt_param_scheduler = args.use_checkpoint_opt_param_scheduler
        if self.override_opt_param_scheduler:
            assert not self.use_checkpoint_opt_param_scheduler, (
                "both override and " "use-checkpoint are set."
            )

        # Set the learning rate
        self.step(0)

    def get_wd(self):
        """Weight decay incr functions"""
        if self.num_steps > self.wd_incr_steps:
            return self.end_wd

        if self.wd_incr_style == "constant":
            assert self.start_wd == self.end_wd
            return self.end_wd

        incr_ratio = float(self.num_steps) / float(self.wd_incr_steps)
        assert 0.0 <= incr_ratio <= 1.0

        if self.wd_incr_style == "linear":
            coeff = incr_ratio
        elif self.wd_incr_style == "cosine":
            coeff = 0.5 * (math.cos(math.pi * (1 - incr_ratio)) + 1.0)
        else:
            raise Exception(
                "{} weight decay increment style is not supported.".format(
                    self.wd_incr_style
                )
            )

        return self.start_wd + coeff * (self.end_wd - self.start_wd)

    def get_grad_accum_step(self):
        """grad_accum_step incr functions"""
        if self.num_steps > self.grad_incr_steps:
            return self.end_grad_accum

        if self.grad_accum_step_incr_style == "constant":
            assert self.start_grad_accum == self.end_grad_accum
            return self.end_grad_accum

        incr_ratio = float(self.num_steps) / float(self.grad_incr_steps)
        assert 0.0 <= incr_ratio <= 1.0

        if self.grad_accum_step_incr_style == "linear":
            coeff = incr_ratio
        elif self.grad_accum_step_incr_style == "power":
            coeff = 1 - math.pow(0.1, incr_ratio)
        else:
            raise Exception(
                "{} grad accum step increment style is not supported.".format(
                    self.grad_accum_step_incr_style
                )
            )
        
        return int(self.start_grad_accum + coeff * (self.end_grad_accum - self.start_grad_accum))
    
    
    def get_lr(self):
        """Learning rate decay functions adapted from:"""

        # Use linear warmup for the initial part.
        if self.lr_warmup_steps > 0 and self.num_steps <= self.lr_warmup_steps:
            return self.begin_lr + (self.max_lr - self.begin_lr) * float(self.num_steps) / float(self.lr_warmup_steps)

        # If the learning rate is constant, just return the initial value.
        if self.lr_decay_style == "constant":
            assert self.max_lr == self.min_lr == self.begin_lr
            return self.max_lr

        # For any steps larger than `self.lr_decay_steps`, use `self.min_lr`.
        if self.num_steps > self.lr_decay_steps:
            return self.min_lr

        # If we are done with the warmup period, use the decay style.
        decay_ratio = float(self.num_steps - self.lr_warmup_steps) / float(self.lr_decay_steps)
        assert 0.0 <= decay_ratio <= 1.0
        delta_lr = self.max_lr - self.min_lr

        if self.lr_decay_style == "linear":
            coeff = 1.0 - decay_ratio
        elif self.lr_decay_style == "cosine":
            coeff = 0.5 * (math.cos(math.pi * decay_ratio) + 1.0)
        else:
            raise Exception(
                "{} decay style is not supported.".format(self.lr_decay_style)
            )

        return self.min_lr + coeff * delta_lr

    def step(self, increment):
        """Set lr for all parameters groups."""
        self.num_steps += increment
        new_lr = self.get_lr()
        new_wd = self.get_wd()
        new_grad_accum_step = self.get_grad_accum_step()
        for group in self.optimizer.param_groups:
            assert group.get("lr_mult", 1.0) == 1
            group["lr"] = new_lr * group.get("lr_mult", 1.0)
            if group["weight_decay"] != 0:
                group["weight_decay"] = new_wd * group.get("wd_mult", 1.0)
        return new_lr, new_grad_accum_step

    def state_dict(self):
        state_dict = {
            "num_steps": self.num_steps,
            "begin_lr": self.begin_lr,
            "max_lr": self.max_lr,
            "lr_warmup_steps": self.lr_warmup_steps,
            "lr_decay_steps": self.lr_decay_steps,
            "lr_decay_factor": self.lr_decay_factor,
            "lr_decay_style": self.lr_decay_style,
            "start_wd": self.start_wd,
            "end_wd": self.end_wd,
            "wd_incr_steps": self.wd_incr_steps,
            "wd_incr_style": self.wd_incr_style,
            "start_grad_accum": self.start_grad_accum,
            "end_grad_accum": self.end_grad_accum,
            "grad_incr_steps": self.grad_incr_steps,
            "grad_accum_step_incr_style": self.grad_accum_step_incr_style,
        }
        return state_dict

    def _check_and_set(self, cls_value, sd_value, name):
        """Auxiliary function for checking the values in the checkpoint and
        setting them."""
        if self.override_opt_param_scheduler:
            if self.rank == 0:
                print(f" > overriding {name} value form {sd_value} to {cls_value}")
            return cls_value

        if not self.use_checkpoint_opt_param_scheduler:
            assert cls_value == sd_value, (
                f"OptimizerParamScheduler: class input value {cls_value} and checkpoint"
                f"value {sd_value} for {name} do not match"
            )
        if self.rank == 0:
            print(f" > using checkpoint value {sd_value} for {name}")
        return sd_value

    def load_state_dict(self, sd):
        # lr paras
        self.lr_decay_factor = self._check_and_set(
            self.lr_decay_factor, sd["lr_decay_factor"], "lr decay factor"
        )
        self.begin_lr = self._check_and_set(
            self.begin_lr, sd["begin_lr"], "initial learning rate"
        )
        self.max_lr = self._check_and_set(
            self.max_lr, sd["max_lr"], "maximum learning rate"
        )
        self.min_lr = self.max_lr/self.lr_decay_factor
        
        self.lr_warmup_steps = self._check_and_set(
            self.lr_warmup_steps, sd["lr_warmup_steps"], "warmup iterations"
        )

        self.lr_decay_steps = self._check_and_set(
            self.lr_decay_steps, sd["lr_decay_steps"], "number of lr_decay iterations"
        )

        self.lr_decay_style = self._check_and_set(
            self.lr_decay_style, sd["lr_decay_style"], "learning rate decay style"
        )

        num_steps = int(sd["num_steps"] * (self.lr_warmup_steps/sd["lr_warmup_steps"]))
        self.step(increment=num_steps)
        if self.rank == 0:
            sd_num_steps = sd['num_steps']
            print(f" > set num_steps value form {sd_num_steps} to {num_steps}")

        # wd paras
        if "start_wd" in sd:
            self.start_wd = self._check_and_set(
                self.start_wd, sd["start_wd"], "start weight decay"
            )
            self.end_wd = self._check_and_set(
                self.end_wd, sd["end_wd"], "end weight decay"
            )
            self.wd_incr_steps = self._check_and_set(
                self.wd_incr_steps,
                sd["wd_incr_steps"],
                "total number of weight decay iterations",
            )
            self.wd_incr_style = self._check_and_set(
                self.wd_incr_style, 
                sd["wd_incr_style"], 
                "weight decay incr style"
            )

        # grad accum para
        if "start_grad_accum" in sd:
            self.start_grad_accum = self._check_and_set(
                self.start_grad_accum, sd["start_grad_accum"], "start grad accum step"
            )
            self.end_grad_accum = self._check_and_set(
                self.end_grad_accum, sd["end_grad_accum"], "end grad accum step"
            )
            self.grad_incr_steps = self._check_and_set(
                self.grad_incr_steps,
                sd["grad_incr_steps"],
                "total number of grad incr iterations",
            )
            self.grad_accum_step_incr_style = self._check_and_set(
                self.grad_accum_step_incr_style, 
                sd["grad_accum_step_incr_style"], 
                "grad accum step incr style"
            )