class_docstr: Implements a pytorch variant of Adan
  Adan was proposed in
  Adan: Adaptive Nesterov Momentum Algorithm for
      Faster Optimizing Deep Models[J].arXiv preprint arXiv:2208.06677, 2022.
  https://arxiv.org/abs/2208.06677
  Arguments:
      params (iterable): iterable of parameters to optimize or
          dicts defining parameter groups.
      lr (float, optional): learning rate. (default: 1e-3)
      betas (Tuple[float, float, flot], optional): coefficients used for
          first- and second-order moments. (default: (0.98, 0.92, 0.99))
      eps (float, optional): term added to the denominator to improve
          numerical stability. (default: 1e-8)
      weight_decay (float, optional): decoupled weight decay
          (L2 penalty) (default: 0)
      max_grad_norm (float, optional): value used to clip
          global grad norm (default: 0.0 no clip)
      no_prox (bool): how to perform the decoupled weight decay
          (default: False)
      foreach (bool): if True would use torch._foreach implementation.
          It's faster but uses slightly more memory. (default: True)
      fused (bool, optional): whether fused implementation is used.
          (default: False)
class_docstr_tok: ["Implements","a","pytorch","variant","of","Adan","Adan","was","proposed","in","Adan",":","Adaptive","Nesterov","Momentum","Algorithm","for","Faster","Optimizing","Deep","Models","[","J","]",".arXiv","preprint","arXiv:2208.06677",",","2022.","https",":","\/\/arxiv.org\/abs\/2208.06677","Arguments",":","params","(","iterable",")",":","iterable","of","parameters","to","optimize","or","dicts","defining","parameter","groups",".","lr","(","float",",","optional",")",":","learning","rate",".","(","default",":","1e-3",")","betas","(","Tuple","[","float",",","float",",","flot","]",",","optional",")",":","coefficients","used","for","first-","and","second-order","moments",".","(","default",":","(","0.98",",","0.92",",","0.99",")",")","eps","(","float",",","optional",")",":","term","added","to","the","denominator","to","improve","numerical","stability",".","(","default",":","1e-8",")","weight_decay","(","float",",","optional",")",":","decoupled","weight","decay","(","L2","penalty",")","(","default",":","0",")","max_grad_norm","(","float",",","optional",")",":","value","used","to","clip","global","grad","norm","(","default",":","0.0","no","clip",")","no_prox","(","bool",")",":","how","to","perform","the","decoupled","weight","decay","(","default",":","False",")","foreach","(","bool",")",":","if","True","would","use","torch._foreach","implementation",".","It","'s","faster","but","uses","slightly","more","memory",".","(","default",":","True",")","fused","(","bool",",","optional",")",":","whether","fused","implementation","is","used",".","(","default",":","False",")"]
docstr: Performs a single optimization step.
docstr_tok: ["Performs","a","single","optimization","step","."]
code: def step(self, closure=None):
      """Performs a single optimization step."""
  
      loss = None
      if closure is not None:
          with torch.enable_grad():
              loss = closure()
  
      if self.defaults["max_grad_norm"] > 0:
          device = self.param_groups[0]["params"][0].device
          global_grad_norm = torch.zeros(1, device=device)
  
          max_grad_norm = torch.tensor(
              self.defaults["max_grad_norm"], device=device
          )
          for group in self.param_groups:
              for p in group["params"]:
                  if p.grad is not None:
                      grad = p.grad
                      global_grad_norm.add_(grad.pow(2).sum())
  
          global_grad_norm = torch.sqrt(global_grad_norm)
  
          clip_global_grad_norm = torch.clamp(
              max_grad_norm / (global_grad_norm + group["eps"]), max=1.0
          ).item()
      else:
          clip_global_grad_norm = 1.0
  
      for group in self.param_groups:
          params_with_grad = []
          grads = []
          exp_avgs = []
          exp_avg_sqs = []
          exp_avg_diffs = []
          neg_pre_grads = []
  
          beta1, beta2, beta3 = group["betas"]
          # assume same step across group now to simplify things
          # per parameter step can be easily support
          # by making it tensor, or pass list into kernel
          if "step" in group:
              group["step"] += 1
          else:
              group["step"] = 1
  
          bias_correction1 = 1.0 - beta1 ** group["step"]
          bias_correction2 = 1.0 - beta2 ** group["step"]
          bias_correction3 = 1.0 - beta3 ** group["step"]
  
          for p in group["params"]:
              if p.grad is None:
                  continue
              params_with_grad.append(p)
              grads.append(p.grad)
  
              state = self.state[p]
              if len(state) == 0:
                  state["exp_avg"] = torch.zeros_like(p)
                  state["exp_avg_sq"] = torch.zeros_like(p)
                  state["exp_avg_diff"] = torch.zeros_like(p)
  
              if "neg_pre_grad" not in state or group["step"] == 1:
                  state["neg_pre_grad"] = p.grad.clone().mul_(
                      -clip_global_grad_norm
                  )
  
              exp_avgs.append(state["exp_avg"])
              exp_avg_sqs.append(state["exp_avg_sq"])
              exp_avg_diffs.append(state["exp_avg_diff"])
              neg_pre_grads.append(state["neg_pre_grad"])
  
          kwargs = dict(
              params=params_with_grad,
              grads=grads,
              exp_avgs=exp_avgs,
              exp_avg_sqs=exp_avg_sqs,
              exp_avg_diffs=exp_avg_diffs,
              neg_pre_grads=neg_pre_grads,
              beta1=beta1,
              beta2=beta2,
              beta3=beta3,
              bias_correction1=bias_correction1,
              bias_correction2=bias_correction2,
              bias_correction3_sqrt=math.sqrt(bias_correction3),
              lr=group["lr"],
              weight_decay=group["weight_decay"],
              eps=group["eps"],
              no_prox=group["no_prox"],
              clip_global_grad_norm=clip_global_grad_norm,
          )
  
          if group["foreach"]:
              if group["fused"]:
                  if torch.cuda.is_available():
                      _fused_adan_multi_tensor(**kwargs)
                  else:
                      raise ValueError(
                          "Fused Adan does not support CPU"
                      )
              else:
                  _multi_tensor_adan(**kwargs)
          elif group["fused"]:
              if torch.cuda.is_available():
                  _fused_adan_single_tensor(**kwargs)
              else:
                  raise ValueError("Fused Adan does not support CPU")
          else:
              _single_tensor_adan(**kwargs)
  
      return loss
  
file_path: NeMo/nemo/core/optim/adan.py
imports: import math
  from typing import List
  import torch
  from torch import Tensor
  from torch.optim.optimizer import Optimizer
label_desc: Use image node_id 4 for calling the Adan obj's underlying member method code with example usage: obj.step(closure) and returns: loss