


'''simple docstring'''






import contextlib
import copy
import random
from typing import Any, Dict, Iterable, Optional, Union

import numpy as np
import torch

from .utils import deprecate, is_transformers_available


if is_transformers_available():
  import transformers







def 				UpperCamelCase_			(    A__					:   int					):
  '''simple docstring'''





  random.seed(A__					)
  np.random.seed(A__					)
  torch.manual_seed(A__					)
  torch.cuda.manual_seed_all(A__					)
  # ^^ safe to call this function even if cuda is not available






class    __snake_case       :







    """simple docstring"""



    def __init__(   self    :  List[str]    ,						lowerCamelCase    :  Iterable[torch.nn.Parameter]    ,						lowerCamelCase    :  float = 0.9_999    ,						lowerCamelCase    :  float = 0.0    ,						lowerCamelCase    :  int = 0    ,						lowerCamelCase    :  bool = False    ,						lowerCamelCase    :  Union[float, int] = 1.0    ,						lowerCamelCase    :  Union[float, int] = 2 / 3    ,						lowerCamelCase    :  Optional[Any] = None    ,						lowerCamelCase    :  Dict[str, Any] = None    ,						**lowerCamelCase    :  int    ,						)   ->  str:

      if isinstance(lowerCamelCase    ,						torch.nn.Module		):
        lowerCAmelCase_			:      List[Any]			=   (
            """Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. """
            """Please pass the parameters of the module instead."""
        )
        deprecate(
            """passing a `torch.nn.Module` to `ExponentialMovingAverage`"""    ,						"""1.0.0"""    ,						lowerCamelCase    ,						standard_warn=lowerCamelCase    ,						)
        lowerCAmelCase_			:      List[str]			=   parameters.parameters()

        # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility
        lowerCAmelCase_			:      List[Any]			=   True

      if kwargs.get("""max_value"""    ,						lowerCamelCase		) is not None:
        lowerCAmelCase_			:      Optional[int]			=   """The `max_value` argument is deprecated. Please use `decay` instead."""
        deprecate("""max_value"""    ,						"""1.0.0"""    ,						lowerCamelCase    ,						standard_warn=lowerCamelCase		)
        lowerCAmelCase_			:      Tuple			=   kwargs["""max_value"""]

      if kwargs.get("""min_value"""    ,						lowerCamelCase		) is not None:
        lowerCAmelCase_			:      Optional[Any]			=   """The `min_value` argument is deprecated. Please use `min_decay` instead."""
        deprecate("""min_value"""    ,						"""1.0.0"""    ,						lowerCamelCase    ,						standard_warn=lowerCamelCase		)
        lowerCAmelCase_			:      List[str]			=   kwargs["""min_value"""]

      lowerCAmelCase_			:      str			=   list(lowerCamelCase		)
      lowerCAmelCase_			:      Dict			=   [p.clone().detach() for p in parameters]

      if kwargs.get("""device"""    ,						lowerCamelCase		) is not None:
        lowerCAmelCase_			:      List[Any]			=   """The `device` argument is deprecated. Please use `to` instead."""
        deprecate("""device"""    ,						"""1.0.0"""    ,						lowerCamelCase    ,						standard_warn=lowerCamelCase		)
        self.to(device=kwargs["""device"""]		)

      lowerCAmelCase_			:      List[Any]			=   None

      lowerCAmelCase_			:      Optional[int]			=   decay
      lowerCAmelCase_			:      List[Any]			=   min_decay
      lowerCAmelCase_			:      Dict			=   update_after_step
      lowerCAmelCase_			:      List[Any]			=   use_ema_warmup
      lowerCAmelCase_			:      Union[str, Any]			=   inv_gamma
      lowerCAmelCase_			:      Optional[int]			=   power
      lowerCAmelCase_			:      List[Any]			=   0
      lowerCAmelCase_			:      int			=   None  # set in `step()`

      lowerCAmelCase_			:      str			=   model_cls
      lowerCAmelCase_			:      str			=   model_config

    @classmethod
    def __lowercase   (   cls    :  Optional[int]    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  Tuple		)   ->  "EMAModel":
      lowerCAmelCase_,							lowerCAmelCase_			:      List[Any]			=   model_cls.load_config(lowerCamelCase    ,						return_unused_kwargs=lowerCamelCase		)
      lowerCAmelCase_			:      List[str]			=   model_cls.from_pretrained(lowerCamelCase		)

      lowerCAmelCase_			:      int			=   cls(model.parameters()    ,						model_cls=lowerCamelCase    ,						model_config=model.config		)

      ema_model.load_state_dict(lowerCamelCase		)
      return ema_model

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  Optional[Any]		)   ->  Tuple:
      if self.model_cls is None:
        raise ValueError("""`save_pretrained` can only be used if `model_cls` was defined at __init__."""		)

      if self.model_config is None:
        raise ValueError("""`save_pretrained` can only be used if `model_config` was defined at __init__."""		)

      lowerCAmelCase_			:      Dict			=   self.model_cls.from_config(self.model_config		)
      lowerCAmelCase_			:      str			=   self.state_dict()
      state_dict.pop("""shadow_params"""    ,						lowerCamelCase		)

      model.register_to_config(**lowerCamelCase		)
      self.copy_to(model.parameters()		)
      model.save_pretrained(lowerCamelCase		)

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  int		)   ->  float:
      lowerCAmelCase_			:      Any			=   max(0    ,						optimization_step - self.update_after_step - 1		)

      if step <= 0:
        return 0.0

      if self.use_ema_warmup:
        lowerCAmelCase_			:      Union[str, Any]			=   1 - (1 + step / self.inv_gamma) ** -self.power
      else:
        lowerCAmelCase_			:      Optional[int]			=   (1 + step) / (10 + step)

      lowerCAmelCase_			:      Optional[int]			=   min(lowerCamelCase    ,						self.decay		)
      # make sure decay is not smaller than min_decay
      lowerCAmelCase_			:      Optional[int]			=   max(lowerCamelCase    ,						self.min_decay		)
      return cur_decay_value

    @torch.no_grad()
    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  Iterable[torch.nn.Parameter]		)   ->  Dict:
      if isinstance(lowerCamelCase    ,						torch.nn.Module		):
        lowerCAmelCase_			:      Union[str, Any]			=   (
            """Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. """
            """Please pass the parameters of the module instead."""
        )
        deprecate(
            """passing a `torch.nn.Module` to `ExponentialMovingAverage.step`"""    ,						"""1.0.0"""    ,						lowerCamelCase    ,						standard_warn=lowerCamelCase    ,						)
        lowerCAmelCase_			:      int			=   parameters.parameters()

      lowerCAmelCase_			:      List[Any]			=   list(lowerCamelCase		)

      self.optimization_step += 1

      # Compute the decay factor for the exponential moving average.
      lowerCAmelCase_			:      Optional[Any]			=   self.get_decay(self.optimization_step		)
      lowerCAmelCase_			:      Any			=   decay
      lowerCAmelCase_			:      Any			=   1 - decay

      lowerCAmelCase_			:      Dict			=   contextlib.nullcontext
      if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
        import deepspeed

      for s_param, param in zip(self.shadow_params    ,						lowerCamelCase		):
        if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled():
          lowerCAmelCase_			:      Dict			=   deepspeed.zero.GatheredParameters(lowerCamelCase    ,						modifier_rank=lowerCamelCase		)

        with context_manager():
          if param.requires_grad:
            s_param.sub_(one_minus_decay * (s_param - param)		)
          else:
            s_param.copy_(lowerCamelCase		)

    def __lowercase   (   self    :  str    ,						lowerCamelCase    :  Iterable[torch.nn.Parameter]		)   ->  None:
      lowerCAmelCase_			:      Union[str, Any]			=   list(lowerCamelCase		)
      for s_param, param in zip(self.shadow_params    ,						lowerCamelCase		):
        param.data.copy_(s_param.to(param.device		).data		)

    def __lowercase   (   self    :  Optional[int]    ,						lowerCamelCase    :  List[str]=None    ,						lowerCamelCase    :  Dict=None		)   ->  None:
      lowerCAmelCase_			:      str			=   [
          p.to(device=lowerCamelCase    ,						dtype=lowerCamelCase		) if p.is_floating_point() else p.to(device=lowerCamelCase		)
          for p in self.shadow_params
      ]

    def __lowercase   (   self    :  Dict		)   ->  dict:
      return {
          "decay": self.decay,
          "min_decay": self.min_decay,
          "optimization_step": self.optimization_step,
          "update_after_step": self.update_after_step,
          "use_ema_warmup": self.use_ema_warmup,
          "inv_gamma": self.inv_gamma,
          "power": self.power,
          "shadow_params": self.shadow_params,
      }

    def __lowercase   (   self    :  int    ,						lowerCamelCase    :  Iterable[torch.nn.Parameter]		)   ->  None:
      lowerCAmelCase_			:      List[str]			=   [param.detach().cpu().clone() for param in parameters]

    def __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  Iterable[torch.nn.Parameter]		)   ->  None:
      if self.temp_stored_params is None:
        raise RuntimeError("""This ExponentialMovingAverage has no `store()`ed weights """ """to `restore()`"""		)
      for c_param, param in zip(self.temp_stored_params    ,						lowerCamelCase		):
        param.data.copy_(c_param.data		)

      # Better memory-wise.
      lowerCAmelCase_			:      Dict			=   None





    def __lowercase   (   self    :  Dict    ,						lowerCamelCase    :  dict		)   ->  None:
      lowerCAmelCase_			:      List[Any]			=   copy.deepcopy(lowerCamelCase		)

      lowerCAmelCase_			:      int			=   state_dict.get("""decay"""    ,						self.decay		)
      if self.decay < 0.0 or self.decay > 1.0:
        raise ValueError("""Decay must be between 0 and 1"""		)

      lowerCAmelCase_			:      List[Any]			=   state_dict.get("""min_decay"""    ,						self.min_decay		)
      if not isinstance(self.min_decay    ,						lowerCamelCase		):
        raise ValueError("""Invalid min_decay"""		)

      lowerCAmelCase_			:      int			=   state_dict.get("""optimization_step"""    ,						self.optimization_step		)
      if not isinstance(self.optimization_step    ,						lowerCamelCase		):
        raise ValueError("""Invalid optimization_step"""		)

      lowerCAmelCase_			:      List[str]			=   state_dict.get("""update_after_step"""    ,						self.update_after_step		)
      if not isinstance(self.update_after_step    ,						lowerCamelCase		):
        raise ValueError("""Invalid update_after_step"""		)

      lowerCAmelCase_			:      List[str]			=   state_dict.get("""use_ema_warmup"""    ,						self.use_ema_warmup		)
      if not isinstance(self.use_ema_warmup    ,						lowerCamelCase		):
        raise ValueError("""Invalid use_ema_warmup"""		)

      lowerCAmelCase_			:      Optional[Any]			=   state_dict.get("""inv_gamma"""    ,						self.inv_gamma		)
      if not isinstance(self.inv_gamma    ,						(float, int)		):
        raise ValueError("""Invalid inv_gamma"""		)

      lowerCAmelCase_			:      List[str]			=   state_dict.get("""power"""    ,						self.power		)
      if not isinstance(self.power    ,						(float, int)		):
        raise ValueError("""Invalid power"""		)

      lowerCAmelCase_			:      int			=   state_dict.get("""shadow_params"""    ,						lowerCamelCase		)
      if shadow_params is not None:
        lowerCAmelCase_			:      Optional[Any]			=   shadow_params
        if not isinstance(self.shadow_params    ,						lowerCamelCase		):
          raise ValueError("""shadow_params must be a list"""		)
        if not all(isinstance(lowerCamelCase    ,						torch.Tensor		) for p in self.shadow_params		):
          raise ValueError("""shadow_params must all be Tensors"""		)







'''simple docstring'''






from math import ceil







def 				UpperCamelCase_			(    A__					:   int = 10_01					):
  '''simple docstring'''





  lowerCAmelCase_			:      List[Any]			=   1

  for i in range(1							,    int(ceil(n / 2.0					)					)					):
    lowerCAmelCase_			:      int			=   2 * i + 1
    lowerCAmelCase_			:      Tuple			=   2 * i
    lowerCAmelCase_			:      Tuple			=   total + 4 * odd**2 - 6 * even

  return total


if __name__ == "__main__":
  import sys

  if len(sys.argv) == 1:
    print(solution())
  else:
    try:
      __A					:  str											=      int(sys.argv[1])
      print(solution(n))
    except ValueError:
      print("Invalid entry - please enter a number")



