

'''simple docstring'''

import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available





def 				lowercase (					__magic_name__			,   __magic_name__			,   __magic_name__			,   __magic_name__=None							):



					'''simple docstring'''







					UpperCAmelCase		:							List[str]        =       None
					# Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
					if str(weight.dtype							) == "torch.bfloat16":
										# Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
										UpperCAmelCase		:							List[Any]        =       weight.view(torch.intaa							)
										UpperCAmelCase		:							str        =       "bfloat16"
					UpperCAmelCase		:							Dict        =       weight.cpu().numpy()
					UpperCAmelCase		:							Union[str, Any]        =       os.path.join(__magic_name__			,   F"{weight_name}.dat"							)
					if index is not None:
										if dtype is None:
															UpperCAmelCase		:							Optional[int]        =       str(array.dtype							)
										UpperCAmelCase		:							Optional[int]        =       {"dtype": dtype, "shape": list(array.shape							)}
					if array.ndim == 0:
										UpperCAmelCase		:							int        =       array[None]
					UpperCAmelCase		:							List[Any]        =       np.memmap(__magic_name__			,   dtype=array.dtype			,   mode="w+"			,   shape=array.shape							)
					UpperCAmelCase		:							int        =       array[:]
					file_array.flush()
					return index





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







					UpperCAmelCase		:							Dict        =       tuple(weight_info["shape"]							)
					if shape == ():
										# NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
										UpperCAmelCase		:							Any        =       (1,)

					UpperCAmelCase		:							List[str]        =       weight_info["dtype"]
					if dtype == "bfloat16":
										# NumPy does not support bfloat16 so this was saved as a int16
										UpperCAmelCase		:							List[str]        =       "int16"

					UpperCAmelCase		:							Tuple        =       np.memmap(__magic_name__			,   dtype=__magic_name__			,   shape=__magic_name__			,   mode="r"							)

					if len(weight_info["shape"]							) == 0:
										UpperCAmelCase		:							str        =       weight[0]
					UpperCAmelCase		:							str        =       torch.tensor(__magic_name__							)
					if weight_info["dtype"] == "bfloat16":
										UpperCAmelCase		:							Union[str, Any]        =       weight.view(torch.bfloataa							)

					return weight





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







					if index is None or len(__magic_name__							) == 0:
										# Nothing to save
										return

					UpperCAmelCase		:							Optional[Any]        =       os.path.join(__magic_name__			,   "index.json"							)
					if os.path.isfile(__magic_name__							):
										with open(__magic_name__			,   "r"			,   encoding="utf-8"							) as f:
															UpperCAmelCase		:							Dict        =       json.load(__magic_name__							)
					else:
										UpperCAmelCase		:							Optional[int]        =       {}
					current_index.update(__magic_name__							)

					with open(__magic_name__			,   "w"			,   encoding="utf-8"							) as f:
										json.dump(__magic_name__			,   __magic_name__			,   indent=2							)





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







					os.makedirs(__magic_name__			,   exist_ok=__magic_name__							)
					UpperCAmelCase		:							int        =       {}
					for name, parameter in state_dict.items():
										UpperCAmelCase		:							Optional[Any]        =       offload_weight(__magic_name__			,   __magic_name__			,   __magic_name__			,   index=__magic_name__							)

					# Update index
					save_offload_index(__magic_name__			,   __magic_name__							)







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       dataset
							UpperCAmelCase		:							str        =       prefix







		def __getitem__(			self   ,      snake_case      ):


							'''simple docstring'''

							return self.dataset[f"{self.prefix}{key}"]







		def __iter__(			self      ):


							'''simple docstring'''

							return iter([key for key in self.dataset if key.startswith(self.prefix      )]      )







		def __len__(			self      ):


							'''simple docstring'''

							return len(self.dataset      )







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		def __init__(			self   ,      snake_case = None   ,      snake_case = None   ,      snake_case = None   ,      snake_case=None   ,      ):


							'''simple docstring'''

							if state_dict is None and save_folder is None:
												raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."      )

							UpperCAmelCase		:							int        =       {} if state_dict is None else state_dict
							UpperCAmelCase		:							Dict        =       save_folder
							if index is None and save_folder is not None:
												with open(os.path.join(snake_case   ,      "index.json"      )      ) as f:
																	UpperCAmelCase		:							Tuple        =       json.load(snake_case      )
							UpperCAmelCase		:							int        =       {} if index is None else index
							UpperCAmelCase		:							Tuple        =       list(self.state_dict.keys()      )
							self.all_keys.extend([key for key in self.index if key not in self.all_keys]      )
							UpperCAmelCase		:							List[str]        =       device







		def __getitem__(			self   ,      snake_case      ):


							'''simple docstring'''

							if key in self.state_dict:
												return self.state_dict[key]
							UpperCAmelCase		:							Dict        =       self.index[key]
							if weight_info.get("safetensors_file"      ) is not None:
												if not is_safetensors_available():
																	raise ImportError("These offloaded weights require the use of safetensors: `pip install safetensors`."      )

												from safetensors import safe_open

												UpperCAmelCase		:							Dict        =       "cpu" if self.device is None else self.device
												with safe_open(weight_info["safetensors_file"]   ,      framework="pt"   ,      device=snake_case      ) as f:
																	UpperCAmelCase		:							Optional[Any]        =       f.get_tensor(weight_info.get("weight_name"   ,      snake_case      )      )

												if "dtype" in weight_info:
																	return tensor.to(getattr(snake_case   ,      weight_info["dtype"]      )      )
												else:
																	return tensor

							UpperCAmelCase		:							Dict        =       os.path.join(self.save_folder   ,      f"{key}.dat"      )
							return load_offloaded_weight(snake_case   ,      snake_case      )







		def __iter__(			self      ):


							'''simple docstring'''

							return iter(self.all_keys      )







		def __len__(			self      ):


							'''simple docstring'''

							return len(self.all_keys      )





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







					UpperCAmelCase		:							Optional[int]        =       {}
					for module_name in submodule_names:
										# We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
										# submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
										result.update(
										    {
										        key: param
										        for key, param in state_dict.items()
										        if key == module_name or key.startswith(module_name + "."							)
										    }							)
					return result



'''simple docstring'''

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 				lowercase (					__magic_name__							):



					'''simple docstring'''







					UpperCAmelCase		:							Any        =       filter(lambda __magic_name__							: p.requires_grad			,   model.parameters()							)
					UpperCAmelCase		:							Union[str, Any]        =       sum([np.prod(p.size()							) for p in model_parameters]							)
					return params


a       :      int  	=			logging.getLogger(__name__)







class   UpperCamelCase__   (       pl.Callback       ):


		"""simple docstring"""

		def 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]        =       {f"lr_group_{i}": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups      )}
							pl_module.logger.log_metrics(snake_case      )







		@rank_zero_only
		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case=True      ):


							'''simple docstring'''

							logger.info(f"***** {type_path} results at step {trainer.global_step:05d} *****"      )
							UpperCAmelCase		:							Optional[Any]        =       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		:							List[str]        =       Path(pl_module.hparams.output_dir      )
							if type_path == "test":
												UpperCAmelCase		:							Dict        =       od / "test_results.txt"
												UpperCAmelCase		:							Dict        =       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		:							Union[str, Any]        =       od / f"{type_path}_results/{trainer.global_step:05d}.txt"
												UpperCAmelCase		:							int        =       od / f"{type_path}_generations/{trainer.global_step:05d}.txt"
												results_file.parent.mkdir(exist_ok=snake_case      )
												generations_file.parent.mkdir(exist_ok=snake_case      )
							with open(snake_case   ,      "a+"      ) as writer:
												for key in sorted(snake_case      ):
																	if key in ["log", "progress_bar", "preds"]:
																						continue
																	UpperCAmelCase		:							Optional[Any]        =       metrics[key]
																	if isinstance(snake_case   ,      torch.Tensor      ):
																						UpperCAmelCase		:							Union[str, Any]        =       val.item()
																	UpperCAmelCase		:							List[str]        =       f"{key}: {val:.6f}\n"
																	writer.write(snake_case      )

							if not save_generations:
												return

							if "preds" in metrics:
												UpperCAmelCase		:							List[str]        =       "\n".join(metrics["preds"]      )
												generations_file.open("w+"      ).write(snake_case      )







		@rank_zero_only
		def 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							try:
												UpperCAmelCase		:							Tuple        =       pl_module.model.model.num_parameters()
							except AttributeError:
												UpperCAmelCase		:							int        =       pl_module.model.num_parameters()

							UpperCAmelCase		:							List[Any]        =       count_trainable_parameters(snake_case      )
							# 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 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							save_json(pl_module.metrics   ,      pl_module.metrics_save_path      )
							return self._write_logs(snake_case   ,      snake_case   ,      "test"      )







		@rank_zero_only
		def 				A_	(			self   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							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 				lowercase (					__magic_name__			,   __magic_name__			,   __magic_name__=1			,   __magic_name__=False							):



					'''simple docstring'''







					if metric == "rouge2":
										UpperCAmelCase		:							Dict        =       "{val_avg_rouge2:.4f}-{step_count}"
					elif metric == "bleu":
										UpperCAmelCase		:							int        =       "{val_avg_bleu:.4f}-{step_count}"
					elif metric == "loss":
										UpperCAmelCase		:							Tuple        =       "{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		:							int        =       ModelCheckpoint(
					    dirpath=__magic_name__			,   filename=__magic_name__			,   monitor=F"val_{metric}"			,   mode="min" if "loss" in metric else "max"			,   save_top_k=__magic_name__			,   )
					return checkpoint_callback





def 				lowercase (					__magic_name__			,   __magic_name__							):



					'''simple docstring'''







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