



"""simple docstring"""


import copy
from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


if TYPE_CHECKING:
					from ... import PreTrainedTokenizerBase, TensorType

__A   :							Any										=   logging.get_logger(__name__)
class 			_a (					lowerCAmelCase):
			"""simple docstring"""
			UpperCamelCase__			      =	"""vision-encoder-decoder"""
			UpperCamelCase__			      =	True



			def __init__(		self     :    Union[str, Any]				,   **__UpperCamelCase     :    Optional[int]   )->Tuple:
							super().__init__(**__UpperCamelCase   )
							if "encoder" not in kwargs or "decoder" not in kwargs:
											raise ValueError(
											    F'A configuraton of type {self.model_type} cannot be instantiated because '
											    F'not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}'   )

							_UpperCAmelCase					=    kwargs.pop('''encoder'''   )
							_UpperCAmelCase					=    encoder_config.pop('''model_type'''   )
							_UpperCAmelCase					=    kwargs.pop('''decoder'''   )
							_UpperCAmelCase					=    decoder_config.pop('''model_type'''   )

							_UpperCAmelCase					=    AutoConfig.for_model(__UpperCamelCase				,   **__UpperCamelCase   )
							_UpperCAmelCase					=    AutoConfig.for_model(__UpperCamelCase				,   **__UpperCamelCase   )
							_UpperCAmelCase					=    True



			@classmethod
			def  lowercase__						(		cls     :    int				,   __UpperCamelCase     :    PretrainedConfig				,   __UpperCamelCase     :    PretrainedConfig				,   **__UpperCamelCase     :    List[Any]   )->PretrainedConfig:
							logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'''   )
							_UpperCAmelCase					=    True
							_UpperCAmelCase					=    True

							return cls(encoder=encoder_config.to_dict()				,   decoder=decoder_config.to_dict()				,   **__UpperCamelCase   )



			def  lowercase__						(		self     :    Dict   )->int:
							_UpperCAmelCase					=    copy.deepcopy(self.__dict__   )
							_UpperCAmelCase					=    self.encoder.to_dict()
							_UpperCAmelCase					=    self.decoder.to_dict()
							_UpperCAmelCase					=    self.__class__.model_type
							return output



class 			_a (					lowerCAmelCase):
			"""simple docstring"""
			UpperCamelCase__			      =	version.parse("""1.11""")



			@property
			def  lowercase__						(		self     :    Optional[int]   )->Mapping[str, Mapping[int, str]]:
							return OrderedDict(
							    [
							        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
							    ]   )



			@property
			def  lowercase__						(		self     :    List[Any]   )->float:
							return 1e-4



			@property
			def  lowercase__						(		self     :    List[str]   )->Mapping[str, Mapping[int, str]]:
							return OrderedDict({'''last_hidden_state''': {0: '''batch''', 1: '''encoder_sequence'''}}   )



class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			@property
			def  lowercase__						(		self     :    List[str]   )->Mapping[str, Mapping[int, str]]:
							_UpperCAmelCase					=    OrderedDict()
							_UpperCAmelCase					=    {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
							_UpperCAmelCase					=    {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
							_UpperCAmelCase					=    {0: '''batch''', 1: '''encoder_sequence'''}

							return common_inputs



			def  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    "PreTrainedTokenizerBase"				,   __UpperCamelCase     :    int = -1				,   __UpperCamelCase     :    int = -1				,   __UpperCamelCase     :    bool = False				,   __UpperCamelCase     :    Optional["TensorType"] = None				,   )->Mapping[str, Any]:
							import torch

							_UpperCAmelCase					=    OrderedDict()

							_UpperCAmelCase					=    super().generate_dummy_inputs(
							    __UpperCamelCase				,   batch_size=__UpperCamelCase				,   seq_length=__UpperCamelCase				,   is_pair=__UpperCamelCase				,   framework=__UpperCamelCase   )

							_UpperCAmelCase		,						_UpperCAmelCase					=    dummy_input['''input_ids'''].shape
							_UpperCAmelCase					=    (batch, encoder_sequence, self._config.encoder_hidden_size)
							_UpperCAmelCase					=    dummy_input.pop('''input_ids'''   )
							_UpperCAmelCase					=    dummy_input.pop('''attention_mask'''   )
							_UpperCAmelCase					=    torch.zeros(__UpperCamelCase   )

							return common_inputs



class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			@property
			def  lowercase__						(		self     :    List[Any]   )->None:
							pass



			def  lowercase__						(		self     :    Any				,   __UpperCamelCase     :    PretrainedConfig   )->OnnxConfig:
							return VisionEncoderDecoderEncoderOnnxConfig(__UpperCamelCase   )



			def  lowercase__						(		self     :    Tuple				,   __UpperCamelCase     :    PretrainedConfig				,   __UpperCamelCase     :    PretrainedConfig				,   __UpperCamelCase     :    str = "default"   )->OnnxConfig:
							_UpperCAmelCase					=    encoder_config.hidden_size
							return VisionEncoderDecoderDecoderOnnxConfig(__UpperCamelCase				,   __UpperCamelCase   )








"""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")



