



'''simple docstring'''







import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


SCREAMING_SNAKE_CASE__     : Optional[int]				=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__     : int				=   [
    """yjernite/retribert-base-uncased""",
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]




class 				__lowerCAmelCase(							lowerCAmelCase__      ):
			__snake_case  :		Dict		=      RetriBertConfig
			__snake_case  :		List[Any]		=      None
			__snake_case  :		Union[str, Any]		=      'retribert'






			def 				_lowercase	(   self  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							List[Any]	):




					"""simple docstring"""







					if isinstance(SCREAMING_SNAKE_CASE      ,       nn.Linear	):
							module.weight.data.normal_(mean=0.0      ,       std=self.config.initializer_range	)
							if module.bias is not None:
									module.bias.data.zero_()
					elif isinstance(SCREAMING_SNAKE_CASE      ,       nn.Embedding	):
							module.weight.data.normal_(mean=0.0      ,       std=self.config.initializer_range	)
							if module.padding_idx is not None:
									module.weight.data[module.padding_idx].zero_()
					elif isinstance(SCREAMING_SNAKE_CASE      ,       nn.LayerNorm	):
							module.bias.data.zero_()
							module.weight.data.fill_(1.0	)


SCREAMING_SNAKE_CASE__     : str				=   r"""

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""




@add_start_docstrings(
    'Bert Based model to embed queries or document for document retrieval.'		,			lowerCAmelCase__		,			)
class 				__lowerCAmelCase(							lowerCAmelCase__      ):






			def __init__(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							RetriBertConfig	):




					"""simple docstring"""







					super().__init__(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Any										=      config.projection_dim

					SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      BertModel(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Any										=      None if config.share_encoders else BertModel(SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      nn.Dropout(config.hidden_dropout_prob	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      nn.Linear(config.hidden_size      ,       config.projection_dim      ,       bias=SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Optional[int]										=      nn.Linear(config.hidden_size      ,       config.projection_dim      ,       bias=SCREAMING_SNAKE_CASE	)

					SCREAMING_SNAKE_CASE_						:int										=      nn.CrossEntropyLoss(reduction='mean'	)

					# Initialize weights and apply final processing
					self.post_init()






			def 				_lowercase	(   self  :							Dict      ,       SCREAMING_SNAKE_CASE  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							str      ,       SCREAMING_SNAKE_CASE  :							List[Any]      ,       SCREAMING_SNAKE_CASE  :							Tuple=-1      ,       ):




					"""simple docstring"""







					if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
							return sent_encoder(SCREAMING_SNAKE_CASE      ,       attention_mask=SCREAMING_SNAKE_CASE	)[1]
					else:
							# prepare implicit variables
							SCREAMING_SNAKE_CASE_						:Tuple										=      input_ids.device
							SCREAMING_SNAKE_CASE_						:Any										=      input_ids.size()
							SCREAMING_SNAKE_CASE_						:Any										=      torch.zeros(SCREAMING_SNAKE_CASE      ,       dtype=torch.long      ,       device=SCREAMING_SNAKE_CASE	)
							SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      [None] * sent_encoder.config.num_hidden_layers
							SCREAMING_SNAKE_CASE_						:torch.Tensor										=      sent_encoder.get_extended_attention_mask(
							    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)

							# define function for checkpointing
							def partial_encode(*SCREAMING_SNAKE_CASE  :							Union[str, Any]	):
									SCREAMING_SNAKE_CASE_						:List[Any]										=      sent_encoder.encoder(
									    inputs[0]      ,       attention_mask=inputs[1]      ,       head_mask=SCREAMING_SNAKE_CASE      ,       )
									SCREAMING_SNAKE_CASE_						:int										=      encoder_outputs[0]
									SCREAMING_SNAKE_CASE_						:Optional[Any]										=      sent_encoder.pooler(SCREAMING_SNAKE_CASE	)
									return pooled_output

							# run embedding layer on everything at once
							SCREAMING_SNAKE_CASE_						:Dict										=      sent_encoder.embeddings(
							    input_ids=SCREAMING_SNAKE_CASE      ,       position_ids=SCREAMING_SNAKE_CASE      ,       token_type_ids=SCREAMING_SNAKE_CASE      ,       inputs_embeds=SCREAMING_SNAKE_CASE	)
							# run encoding and pooling on one mini-batch at a time
							SCREAMING_SNAKE_CASE_						:str										=      []
							for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size	)	):
									SCREAMING_SNAKE_CASE_						:Optional[int]										=      embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
									SCREAMING_SNAKE_CASE_						:Optional[Any]										=      extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
									SCREAMING_SNAKE_CASE_						:int										=      checkpoint.checkpoint(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
									pooled_output_list.append(SCREAMING_SNAKE_CASE	)
							return torch.cat(SCREAMING_SNAKE_CASE      ,       dim=0	)






			def 				_lowercase	(   self  :							Optional[Any]      ,       SCREAMING_SNAKE_CASE  :							List[str]      ,       SCREAMING_SNAKE_CASE  :							Any=None      ,       SCREAMING_SNAKE_CASE  :							str=-1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Dict										=      self.embed_sentences_checkpointed(
					    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       self.bert_query      ,       SCREAMING_SNAKE_CASE      ,       )
					return self.project_query(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							str      ,       SCREAMING_SNAKE_CASE  :							Tuple      ,       SCREAMING_SNAKE_CASE  :							List[str]=None      ,       SCREAMING_SNAKE_CASE  :							int=-1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:int										=      self.embed_sentences_checkpointed(
					    SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       self.bert_query if self.bert_doc is None else self.bert_doc      ,       SCREAMING_SNAKE_CASE      ,       )
					return self.project_doc(SCREAMING_SNAKE_CASE	)






			def 				_lowercase	(   self  :							Any      ,       SCREAMING_SNAKE_CASE  :							torch.LongTensor      ,       SCREAMING_SNAKE_CASE  :							Optional[torch.FloatTensor]      ,       SCREAMING_SNAKE_CASE  :							torch.LongTensor      ,       SCREAMING_SNAKE_CASE  :							Optional[torch.FloatTensor]      ,       SCREAMING_SNAKE_CASE  :							int = -1      ,       ):




					"""simple docstring"""







					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      input_ids_query.device
					SCREAMING_SNAKE_CASE_						:Any										=      self.embed_questions(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:List[str]										=      self.embed_answers(SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE      ,       SCREAMING_SNAKE_CASE	)
					SCREAMING_SNAKE_CASE_						:Dict										=      torch.mm(SCREAMING_SNAKE_CASE      ,       a_reps.t()	)
					SCREAMING_SNAKE_CASE_						:str										=      self.ce_loss(SCREAMING_SNAKE_CASE      ,       torch.arange(compare_scores.shape[1]	).to(SCREAMING_SNAKE_CASE	)	)
					SCREAMING_SNAKE_CASE_						:Optional[Any]										=      self.ce_loss(compare_scores.t()      ,       torch.arange(compare_scores.shape[0]	).to(SCREAMING_SNAKE_CASE	)	)
					SCREAMING_SNAKE_CASE_						:Optional[int]										=      (loss_qa + loss_aq) / 2
					return loss





import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer, Trainer, TrainingArguments

import datasets


__lowerCamelCase								=      '''\
@article{eddine2021frugalscore,
  title={FrugalScore: Learning Cheaper, Lighter and Faster Evaluation Metrics for Automatic Text Generation},
  author={Eddine, Moussa Kamal and Shang, Guokan and Tixier, Antoine J-P and Vazirgiannis, Michalis},
  journal={arXiv preprint arXiv:2110.08559},
  year={2021}
}
'''

__lowerCamelCase								=      '''\
FrugalScore is a reference-based metric for NLG models evaluation. It is based on a distillation approach that allows to learn a fixed, low cost version of any expensive NLG metric, while retaining most of its original performance.
'''


__lowerCamelCase								=      '''
Calculates how good are predictions given some references, using certain scores.
Args:
    predictions (list of str): list of predictions to score. Each predictions
        should be a string.
    references (list of str): list of reference for each prediction. Each
        reference should be a string.
    batch_size (int): the batch size for predictions.
    max_length (int): maximum sequence length.
    device (str): either gpu or cpu
Returns:
    scores (list of int): list of scores.
Examples:
    >>> frugalscore = datasets.load_metric("frugalscore")
    >>> results = frugalscore.compute(predictions=[\'hello there\', \'huggingface\'], references=[\'hello world\', \'hugging face\'])
    >>> print([round(s, 3) for s in results["scores"]])
    [0.631, 0.645]
'''


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,			_KWARGS_DESCRIPTION	)
class 	snake_case_			(datasets.Metric	):




       """simple docstring"""






       def 			A_ (  self):

             """simple docstring"""





             return datasets.MetricInfo(
                 description=_DESCRIPTION  ,citation=_CITATION  ,inputs_description=_KWARGS_DESCRIPTION  ,features=datasets.Features(
                     {
                         "predictions": datasets.Value("string"),
                         "references": datasets.Value("string"),
                     })  ,homepage="https://github.com/moussaKam/FrugalScore"  ,)



       def 			A_ (  self  ,lowercase):

             """simple docstring"""





             if self.config_name == "default":
                   UpperCAmelCase_	:						str					   =		"moussaKam/frugalscore_tiny_bert-base_bert-score"
             else:
                   UpperCAmelCase_	:						Optional[int]					   =		self.config_name
             UpperCAmelCase_	:						Dict					   =		AutoModelForSequenceClassification.from_pretrained(lowercase)
             UpperCAmelCase_	:						str					   =		AutoTokenizer.from_pretrained(lowercase)



       def 			A_ (  self  ,lowercase  ,lowercase  ,lowercase=32  ,lowercase=128  ,lowercase=None  ,):

             """simple docstring"""





             assert len(lowercase) == len(
                 lowercase), "predictions and references should have the same number of sentences."
             if device is not None:
                   assert device in ["gpu", "cpu"], "device should be either gpu or cpu."
             else:
                   UpperCAmelCase_	:						Union[str, Any]					   =		"gpu" if torch.cuda.is_available() else "cpu"
             UpperCAmelCase_	:						Optional[Any]					   =		TrainingArguments(
                 "trainer"  ,fpaa=(device == "gpu")  ,per_device_eval_batch_size=lowercase  ,report_to="all"  ,no_cuda=(device == "cpu")  ,log_level="warning"  ,)
             UpperCAmelCase_	:						List[str]					   =		{"sentence1": predictions, "sentence2": references}
             UpperCAmelCase_	:						List[Any]					   =		datasets.Dataset.from_dict(lowercase)

             def tokenize_function(lowercase):
                   return self.tokenizer(
                       data["sentence1"]  ,data["sentence2"]  ,max_length=lowercase  ,truncation=lowercase  ,padding=lowercase)

             UpperCAmelCase_	:						int					   =		raw_datasets.map(lowercase  ,batched=lowercase)
             tokenized_datasets.remove_columns(["sentence1", "sentence2"])
             UpperCAmelCase_	:						Union[str, Any]					   =		Trainer(self.model  ,lowercase  ,tokenizer=self.tokenizer)
             UpperCAmelCase_	:						Tuple					   =		trainer.predict(lowercase)
             return {"scores": list(predictions.predictions.squeeze(-1))}
