



"""simple docstring"""


from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A   :							Any										=   logging.get_logger(__name__)

__A   :							Dict										=   {
    "huggingface/informer-tourism-monthly": (
        "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}
class 			_a (					lowerCAmelCase):
							"""simple docstring"""
							UpperCamelCase__			      =	"""informer"""
							UpperCamelCase__			      =	{
							    """hidden_size""": """d_model""",
							    """num_attention_heads""": """encoder_attention_heads""",
							    """num_hidden_layers""": """encoder_layers""",
							}



							def __init__(		self     :    List[str]				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    str = "student_t"				,   __UpperCamelCase     :    str = "nll"				,   __UpperCamelCase     :    int = 1				,   __UpperCamelCase     :    List[int] = None				,   __UpperCamelCase     :    Optional[Union[str, bool]] = "mean"				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    int = 6_4				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    bool = True				,   __UpperCamelCase     :    str = "gelu"				,   __UpperCamelCase     :    float = 0.0_5				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    int = 1_0_0				,   __UpperCamelCase     :    float = 0.0_2				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    str = "prob"				,   __UpperCamelCase     :    int = 5				,   __UpperCamelCase     :    bool = True				,   **__UpperCamelCase     :    Union[str, Any]				,   )->Dict:
											# time series specific configuration
											_UpperCAmelCase					=    prediction_length
											_UpperCAmelCase					=    context_length or prediction_length
											_UpperCAmelCase					=    distribution_output
											_UpperCAmelCase					=    loss
											_UpperCAmelCase					=    input_size
											_UpperCAmelCase					=    num_time_features
											_UpperCAmelCase					=    lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
											_UpperCAmelCase					=    scaling
											_UpperCAmelCase					=    num_dynamic_real_features
											_UpperCAmelCase					=    num_static_real_features
											_UpperCAmelCase					=    num_static_categorical_features

											# set cardinality
											if cardinality and num_static_categorical_features > 0:
															if len(__UpperCamelCase   ) != num_static_categorical_features:
																			raise ValueError(
																			    '''The cardinality should be a list of the same length as `num_static_categorical_features`'''   )
															_UpperCAmelCase					=    cardinality
											else:
															_UpperCAmelCase					=    [0]

											# set embedding_dimension
											if embedding_dimension and num_static_categorical_features > 0:
															if len(__UpperCamelCase   ) != num_static_categorical_features:
																			raise ValueError(
																			    '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''   )
															_UpperCAmelCase					=    embedding_dimension
											else:
															_UpperCAmelCase					=    [min(5_0				,   (cat + 1) // 2   ) for cat in self.cardinality]

											_UpperCAmelCase					=    num_parallel_samples

											# Transformer architecture configuration
											_UpperCAmelCase					=    input_size * len(self.lags_sequence   ) + self._number_of_features
											_UpperCAmelCase					=    d_model
											_UpperCAmelCase					=    encoder_attention_heads
											_UpperCAmelCase					=    decoder_attention_heads
											_UpperCAmelCase					=    encoder_ffn_dim
											_UpperCAmelCase					=    decoder_ffn_dim
											_UpperCAmelCase					=    encoder_layers
											_UpperCAmelCase					=    decoder_layers

											_UpperCAmelCase					=    dropout
											_UpperCAmelCase					=    attention_dropout
											_UpperCAmelCase					=    activation_dropout
											_UpperCAmelCase					=    encoder_layerdrop
											_UpperCAmelCase					=    decoder_layerdrop

											_UpperCAmelCase					=    activation_function
											_UpperCAmelCase					=    init_std

											_UpperCAmelCase					=    use_cache

											# Informer
											_UpperCAmelCase					=    attention_type
											_UpperCAmelCase					=    sampling_factor
											_UpperCAmelCase					=    distil

											super().__init__(is_encoder_decoder=__UpperCamelCase				,   **__UpperCamelCase   )



							@property
							def  lowercase__						(		self     :    Optional[int]   )->int:
											return (
											    sum(self.embedding_dimension   )
											    + self.num_dynamic_real_features
											    + self.num_time_features
											    + self.num_static_real_features
											    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
											)








"""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_rag import save_json







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Optional[Any]				):






				'''simple docstring'''



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


__A   :							Dict										=   logging.getLogger(__name__)







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Optional[Any]					,     _SCREAMING_SNAKE_CASE   :						Any				):






				'''simple docstring'''



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

				_UpperCAmelCase					=    ModelCheckpoint(
				    dirpath=_SCREAMING_SNAKE_CASE					,     filename=_SCREAMING_SNAKE_CASE					,     monitor=f'val_{metric}'					,     mode='''max'''					,     save_top_k=3					,     every_n_epochs=1					,     )
				return checkpoint_callback







def  lowercase	(      _SCREAMING_SNAKE_CASE   :						str					,     _SCREAMING_SNAKE_CASE   :						List[str]				):






				'''simple docstring'''



				return EarlyStopping(
				    monitor=f'val_{metric}'					,     mode='''min''' if '''loss''' in metric else '''max'''					,     patience=_SCREAMING_SNAKE_CASE					,     verbose=_SCREAMING_SNAKE_CASE					,     )
class 			_a (					pl.Callback):
			"""simple docstring"""



			def  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    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(__UpperCamelCase   )



			@rank_zero_only
			def  lowercase__						(		self     :    Union[str, Any]				,   __UpperCamelCase     :    pl.Trainer				,   __UpperCamelCase     :    pl.LightningModule				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    Tuple=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=__UpperCamelCase   )
											generations_file.parent.mkdir(exist_ok=__UpperCamelCase   )
							with open(__UpperCamelCase				,   '''a+'''   ) as writer:
											for key in sorted(__UpperCamelCase   ):
															if key in ["log", "progress_bar", "preds"]:
																			continue
															_UpperCAmelCase					=    metrics[key]
															if isinstance(__UpperCamelCase				,   torch.Tensor   ):
																			_UpperCAmelCase					=    val.item()
															_UpperCAmelCase					=    F'{key}: {val:.6f}\n'
															writer.write(__UpperCamelCase   )

							if not save_generations:
											return

							if "preds" in metrics:
											_UpperCAmelCase					=    '''\n'''.join(metrics['''preds''']   )
											generations_file.open('''w+'''   ).write(__UpperCamelCase   )



			@rank_zero_only
			def  lowercase__						(		self     :    Optional[int]				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Dict   )->Union[str, Any]:
							try:
											_UpperCAmelCase					=    pl_module.model.model.num_parameters()
							except AttributeError:
											_UpperCAmelCase					=    pl_module.model.num_parameters()

							_UpperCAmelCase					=    count_trainable_parameters(__UpperCamelCase   )
							# 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  lowercase__						(		self     :    str				,   __UpperCamelCase     :    pl.Trainer				,   __UpperCamelCase     :    pl.LightningModule   )->List[Any]:
							save_json(pl_module.metrics				,   pl_module.metrics_save_path   )
							return self._write_logs(__UpperCamelCase				,   __UpperCamelCase				,   '''test'''   )



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



