




import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only

from utils import save_json



def   lowerCAmelCase						(						_lowerCAmelCase							:				Tuple		):




 """simple docstring"""







 UpperCAmelCase__								=  filter(lambda _lowerCAmelCase		: p.requires_grad  ,							model.parameters()		)
 UpperCAmelCase__								=  sum([np.prod(p.size()		) for p in model_parameters]		)
 return params


_lowerCAmelCase  :				Union[str, Any]						=				logging.getLogger(__name__)
class      _UpperCamelCase (			pl.Callback						):
      def 		UpperCAmelCase_  (     self				:List[Any]	, lowerCamelCase				:Dict	, lowerCamelCase				:str )       ->     Tuple:
       UpperCAmelCase__								=  {f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )}
       pl_module.logger.log_metrics(lowerCamelCase )
      @rank_zero_only
      def 		UpperCAmelCase_  (     self				:Dict	, lowerCamelCase				:pl.Trainer	, lowerCamelCase				:pl.LightningModule	, lowerCamelCase				:str	, lowerCamelCase				:int=True )       ->     None:
       logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****''' )
       UpperCAmelCase__								=  trainer.callback_metrics
       trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} )
       # Log results
       UpperCAmelCase__								=  Path(pl_module.hparams.output_dir )
       if type_path == "test":
        UpperCAmelCase__								=  od / "test_results.txt"
        UpperCAmelCase__								=  od / "test_generations.txt"
       else:
        # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
        # If people want this it will be easy enough to add back.
        UpperCAmelCase__								=  od / f'''{type_path}_results/{trainer.global_step:05d}.txt'''
        UpperCAmelCase__								=  od / f'''{type_path}_generations/{trainer.global_step:05d}.txt'''
        results_file.parent.mkdir(exist_ok=lowerCamelCase )
        generations_file.parent.mkdir(exist_ok=lowerCamelCase )
       with open(lowerCamelCase	, "a+" ) as writer:
        for key in sorted(lowerCamelCase ):
         if key in ["log", "progress_bar", "preds"]:
          continue
         UpperCAmelCase__								=  metrics[key]
         if isinstance(lowerCamelCase	, torch.Tensor ):
          UpperCAmelCase__								=  val.item()
         UpperCAmelCase__								=  f'''{key}: {val:.6f}\n'''
         writer.write(lowerCamelCase )

       if not save_generations:
        return

       if "preds" in metrics:
        UpperCAmelCase__								=  "\n".join(metrics["preds"] )
        generations_file.open("w+" ).write(lowerCamelCase )
      @rank_zero_only
      def 		UpperCAmelCase_  (     self				:Optional[Any]	, lowerCamelCase				:List[str]	, lowerCamelCase				:Any )       ->     List[Any]:
       try:
        UpperCAmelCase__								=  pl_module.model.model.num_parameters()
       except AttributeError:
        UpperCAmelCase__								=  pl_module.model.num_parameters()

       UpperCAmelCase__								=  count_trainable_parameters(lowerCamelCase )
       # mp stands for million parameters
       trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6} )
      @rank_zero_only
      def 		UpperCAmelCase_  (     self				:List[Any]	, lowerCamelCase				:pl.Trainer	, lowerCamelCase				:pl.LightningModule )       ->     Optional[int]:
       save_json(pl_module.metrics	, pl_module.metrics_save_path )
       return self._write_logs(lowerCamelCase	, lowerCamelCase	, "test" )







      @rank_zero_only
      def 		UpperCAmelCase_  (     self				:List[Any]	, lowerCamelCase				:pl.Trainer	, lowerCamelCase				:Union[str, Any] )       ->     Optional[int]:
       save_json(pl_module.metrics	, pl_module.metrics_save_path )
       # Uncommenting this will save val generations
       # return self._write_logs(trainer, pl_module, "valid")



def   lowerCAmelCase						(						_lowerCAmelCase							:				Union[str, Any]  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				Optional[int]=1  ,							_lowerCAmelCase							:				int=False		):




 """simple docstring"""







 if metric == "rouge2":
  UpperCAmelCase__								=  "{val_avg_rouge2:.4f}-{step_count}"
 elif metric == "bleu":
  UpperCAmelCase__								=  "{val_avg_bleu:.4f}-{step_count}"
 elif metric == "loss":
  UpperCAmelCase__								=  "{val_avg_loss:.4f}-{step_count}"
 else:
  raise NotImplementedError(
      F'''seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to'''
      " this function."		)

 UpperCAmelCase__								=  ModelCheckpoint(
     dirpath=_lowerCAmelCase  ,							filename=_lowerCAmelCase  ,							monitor=F'''val_{metric}'''  ,							mode="min" if "loss" in metric else "max"  ,							save_top_k=_lowerCAmelCase  ,							)
 return checkpoint_callback



def   lowerCAmelCase						(						_lowerCAmelCase							:				Any  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 return EarlyStopping(
     monitor=F'''val_{metric}'''  ,							mode="min" if "loss" in metric else "max"  ,							patience=_lowerCAmelCase  ,							verbose=_lowerCAmelCase  ,							)











def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 if a < b:
  return gcd(_lowerCAmelCase  ,							_lowerCAmelCase		)
 if a % b == 0:
  return b
 return gcd(_lowerCAmelCase  ,							a % b		)



def   lowerCAmelCase						(						_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 if y == 0:
  return 1
 UpperCAmelCase__								=  power(_lowerCAmelCase  ,							y // 2  ,							_lowerCAmelCase		) % mod
 UpperCAmelCase__								=  (temp * temp) % mod
 if y % 2 == 1:
  UpperCAmelCase__								=  (temp * x) % mod
 return temp



def   lowerCAmelCase						(						_lowerCAmelCase							:				int		):




 """simple docstring"""







 UpperCAmelCase__								=  2
 while b < n:
  if gcd(_lowerCAmelCase  ,							_lowerCAmelCase		) == 1 and power(_lowerCAmelCase  ,							n - 1  ,							_lowerCAmelCase		) != 1:
   return False
  b += 1
 return True


if __name__ == "__main__":
  _lowerCAmelCase  :				Dict						=				int(input("Enter number: ").strip())
  if is_carmichael_number(number):
    print(F'''{number} is a Carmichael Number.''')
  else:
    print(F'''{number} is not a Carmichael Number.''')





