






'''simple docstring'''





from __future__ import absolute_import, division, print_function, unicode_literals

from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers import RobertaConfig
from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.roberta.modeling_roberta import (
    ROBERTA_INPUTS_DOCSTRING,
    ROBERTA_START_DOCSTRING,
    RobertaEmbeddings,
)

from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy
@add_start_docstrings(
    "The RoBERTa Model transformer with early exiting (DeeRoBERTa). " ,       _UpperCAmelCase ,       )
class 				lowercase       (							_UpperCAmelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							RobertaConfig
    lowerCAmelCase__      				=							"roberta"

    def __init__(					self     :     List[str]				,     __lowerCamelCase     :     Optional[int]     )							->							Union[str, Any]:

     '''simple docstring'''




     super().__init__(lowercase_     )

     lowerCamelCase__  =     RobertaEmbeddings(lowercase_     )
     self.init_weights()
@add_start_docstrings(
    "RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,\n    also takes care of multi-layer training. " ,       _UpperCAmelCase ,       )
class 				lowercase       (							_UpperCAmelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							RobertaConfig
    lowerCAmelCase__      				=							"roberta"

    def __init__(					self     :     List[str]				,     __lowerCamelCase     :     int     )							->							Any:

     '''simple docstring'''




     super().__init__(lowercase_     )
     lowerCamelCase__  =     config.num_labels
     lowerCamelCase__  =     config.num_hidden_layers

     lowerCamelCase__  =     DeeRobertaModel(lowercase_     )
     lowerCamelCase__  =     nn.Dropout(config.hidden_dropout_prob     )
     lowerCamelCase__  =     nn.Linear(config.hidden_size				,     self.config.num_labels     )




    @add_start_docstrings_to_model_forward(lowercase_     )
    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Dict=None				,     __lowerCamelCase     :     int=None				,     __lowerCamelCase     :     Optional[int]=None				,     __lowerCamelCase     :     List[str]=None				,     __lowerCamelCase     :     Tuple=None				,     __lowerCamelCase     :     int=None				,     __lowerCamelCase     :     List[str]=None				,     __lowerCamelCase     :     List[str]=-1				,     __lowerCamelCase     :     Tuple=False				,     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_layers
     try:
      lowerCamelCase__  =     self.roberta(
          lowercase_				,     attention_mask=lowercase_				,     token_type_ids=lowercase_				,     position_ids=lowercase_				,     head_mask=lowercase_				,     inputs_embeds=lowercase_				,     )

      lowerCamelCase__  =     outputs[1]

      lowerCamelCase__  =     self.dropout(lowercase_     )
      lowerCamelCase__  =     self.classifier(lowercase_     )
      lowerCamelCase__  =     (logits,) + outputs[2:]  # add hidden states and attention if they are here
     except HighwayException as e:
      lowerCamelCase__  =     e.message
      lowerCamelCase__  =     e.exit_layer
      lowerCamelCase__  =     outputs[0]

     if not self.training:
      lowerCamelCase__  =     entropy(lowercase_     )
      lowerCamelCase__  =     []
      lowerCamelCase__  =     []
     if labels is not None:
      if self.num_labels == 1:
       #  We are doing regression
       lowerCamelCase__  =     MSELoss()
       lowerCamelCase__  =     loss_fct(logits.view(-1     )				,     labels.view(-1     )     )
      else:
       lowerCamelCase__  =     CrossEntropyLoss()
       lowerCamelCase__  =     loss_fct(logits.view(-1				,     self.num_labels     )				,     labels.view(-1     )     )

      # work with highway exits
      lowerCamelCase__  =     []
      for highway_exit in outputs[-1]:
       lowerCamelCase__  =     highway_exit[0]
       if not self.training:
        highway_logits_all.append(lowercase_     )
        highway_entropy.append(highway_exit[2]     )
       if self.num_labels == 1:
        #  We are doing regression
        lowerCamelCase__  =     MSELoss()
        lowerCamelCase__  =     loss_fct(highway_logits.view(-1     )				,     labels.view(-1     )     )
       else:
        lowerCamelCase__  =     CrossEntropyLoss()
        lowerCamelCase__  =     loss_fct(highway_logits.view(-1				,     self.num_labels     )				,     labels.view(-1     )     )
       highway_losses.append(lowercase_     )

      if train_highway:
       lowerCamelCase__  =     (sum(highway_losses[:-1]     ),) + outputs
       # exclude the final highway, of course
      else:
       lowerCamelCase__  =     (loss,) + outputs
     if not self.training:
      lowerCamelCase__  =     outputs + ((original_entropy, highway_entropy), exit_layer)
      if output_layer >= 0:
       lowerCamelCase__  =     (
           (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:]
       )  # use the highway of the last layer

     return outputs  # (loss), logits, (hidden_states), (attentions), entropy









'''simple docstring'''





import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							"char"
    lowerCAmelCase__      				=							"bpe"
    lowerCAmelCase__      				=							"wp"
__A							:							Any  							=		(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["image_processor", "char_tokenizer"]
    lowerCAmelCase__      				=							"ViTImageProcessor"
    lowerCAmelCase__      				=							"MgpstrTokenizer"

    def __init__(					self     :     Any				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     List[str]=None				,     **__lowerCamelCase     :     Any     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     None
     if "feature_extractor" in kwargs:
      warnings.warn(
          "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
          " instead."				,     __lowerCamelCase				,     )
      lowerCamelCase__  =     kwargs.pop("feature_extractor"     )

     lowerCamelCase__  =     image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
      raise ValueError("You need to specify an `image_processor`."     )
     if tokenizer is None:
      raise ValueError("You need to specify a `tokenizer`."     )

     lowerCamelCase__  =     tokenizer
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("gpt2"     )
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("bert-base-uncased"     )

     super().__init__(__lowerCamelCase				,     __lowerCamelCase     )

    def __call__(					self     :     List[str]				,     __lowerCamelCase     :     Union[str, Any]=None				,     __lowerCamelCase     :     List[Any]=None				,     __lowerCamelCase     :     str=None				,     **__lowerCamelCase     :     Optional[Any]     )							->							str:

     '''simple docstring'''




     if images is None and text is None:
      raise ValueError("You need to specify either an `images` or `text` input to process."     )

     if images is not None:
      lowerCamelCase__  =     self.image_processor(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )
     if text is not None:
      lowerCamelCase__  =     self.char_tokenizer(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )

     if text is None:
      return inputs
     elif images is None:
      return encodings
     else:
      lowerCamelCase__  =     encodings["input_ids"]
      return inputs

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Tuple     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     sequences
     lowerCamelCase__  =     char_preds.size(0     )

     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "char"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "bpe"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "wp"     )

     lowerCamelCase__  =     []
     lowerCamelCase__  =     []
     for i in range(__lowerCamelCase     ):
      lowerCamelCase__  =     [char_scores[i], bpe_scores[i], wp_scores[i]]
      lowerCamelCase__  =     [char_strs[i], bpe_strs[i], wp_strs[i]]
      lowerCamelCase__  =     scores.index(max(__lowerCamelCase     )     )
      final_strs.append(strs[max_score_index]     )
      final_scores.append(scores[max_score_index]     )

     lowerCamelCase__  =     {}
     lowerCamelCase__  =     final_strs
     lowerCamelCase__  =     final_scores
     lowerCamelCase__  =     char_strs
     lowerCamelCase__  =     bpe_strs
     lowerCamelCase__  =     wp_strs
     return out

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Any     )							->							Optional[int]:

     '''simple docstring'''




     if format == DecodeType.CHARACTER:
      lowerCamelCase__  =     self.char_decode
      lowerCamelCase__  =     1
      lowerCamelCase__  =     "[s]"
     elif format == DecodeType.BPE:
      lowerCamelCase__  =     self.bpe_decode
      lowerCamelCase__  =     2
      lowerCamelCase__  =     "#"
     elif format == DecodeType.WORDPIECE:
      lowerCamelCase__  =     self.wp_decode
      lowerCamelCase__  =     102
      lowerCamelCase__  =     "[SEP]"
     else:
      raise ValueError(f'''Format {format} is not supported.'''     )

     lowerCamelCase__  ,	lowerCamelCase__  =     [], []
     lowerCamelCase__  =     pred_logits.size(0     )
     lowerCamelCase__  =     pred_logits.size(1     )
     lowerCamelCase__  ,	lowerCamelCase__  =     pred_logits.topk(1				,     dim=-1				,     largest=__lowerCamelCase				,     sorted=__lowerCamelCase     )
     lowerCamelCase__  =     preds_index.view(-1				,     __lowerCamelCase     )[:, 1:]
     lowerCamelCase__  =     decoder(__lowerCamelCase     )
     lowerCamelCase__  ,	lowerCamelCase__  =     torch.nn.functional.softmax(__lowerCamelCase				,     dim=2     ).max(dim=2     )
     lowerCamelCase__  =     preds_max_prob[:, 1:]

     for index in range(__lowerCamelCase     ):
      lowerCamelCase__  =     preds_str[index].find(__lowerCamelCase     )
      lowerCamelCase__  =     preds_str[index][:pred_eos]
      lowerCamelCase__  =     preds_index[index].cpu().tolist()
      lowerCamelCase__  =     pred_index.index(__lowerCamelCase     ) if eos_token in pred_index else -1
      lowerCamelCase__  =     preds_max_prob[index][: pred_eos_index + 1]
      lowerCamelCase__  =     pred_max_prob.cumprod(dim=0     )[-1] if pred_max_prob.nelement() != 0 else 0.0
      dec_strs.append(__lowerCamelCase     )
      conf_scores.append(__lowerCamelCase     )

     return dec_strs, conf_scores

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Tuple     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.char_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Tuple     )							->							Union[str, Any]:

     '''simple docstring'''




     return self.bpe_tokenizer.batch_decode(__lowerCamelCase     )




    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     int     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.wp_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

