




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). ''' ,  a ,  )
class __snake_case			(			a		):
   UpperCAmelCase__  :    List[str]          =  RobertaConfig
   UpperCAmelCase__  :    str          =  '''roberta'''







   def __init__(      self		:						Dict					,						_snake_case		:						Union[str, Any]):

        """simple docstring"""


        super().__init__(_snake_case)

        UpperCAmelCase_          =							RobertaEmbeddings(_snake_case)
        self.init_weights()







@add_start_docstrings(
    '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top,
    also takes care of multi-layer training. ''' ,  a ,  )
class __snake_case			(			a		):
   UpperCAmelCase__  :    Any          =  RobertaConfig
   UpperCAmelCase__  :    Dict          =  '''roberta'''







   def __init__(      self		:						int					,						_snake_case		:						Tuple):

        """simple docstring"""


        super().__init__(_snake_case)
        UpperCAmelCase_          =							config.num_labels
        UpperCAmelCase_          =							config.num_hidden_layers

        UpperCAmelCase_          =							DeeRobertaModel(_snake_case)
        UpperCAmelCase_          =							nn.Dropout(config.hidden_dropout_prob)
        UpperCAmelCase_          =							nn.Linear(config.hidden_size					,						self.config.num_labels)







   @add_start_docstrings_to_model_forward(_snake_case)
   def lowerCamelCase						(      self		:						Union[str, Any]					,						_snake_case		:						Union[str, Any]=None					,						_snake_case		:						Optional[int]=None					,						_snake_case		:						Tuple=None					,						_snake_case		:						Any=None					,						_snake_case		:						List[str]=None					,						_snake_case		:						int=None					,						_snake_case		:						int=None					,						_snake_case		:						Union[str, Any]=-1					,						_snake_case		:						List[str]=False					,						):

        """simple docstring"""


        UpperCAmelCase_          =							self.num_layers
        try:
             UpperCAmelCase_          =							self.roberta(
                 _snake_case					,						attention_mask=_snake_case					,						token_type_ids=_snake_case					,						position_ids=_snake_case					,						head_mask=_snake_case					,						inputs_embeds=_snake_case					,						)

             UpperCAmelCase_          =							outputs[1]

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

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

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

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

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












import warnings
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class __snake_case			(			a		):
   UpperCAmelCase__  :    Dict          =  ['''image_processor''', '''tokenizer''']
   UpperCAmelCase__  :    Dict          =  '''FlavaImageProcessor'''
   UpperCAmelCase__  :    Dict          =  ('''BertTokenizer''', '''BertTokenizerFast''')







   def __init__(      self		:						Union[str, Any]					,						_snake_case		:						List[str]=None					,						_snake_case		:						str=None					,						**_snake_case		:						int):

        """simple docstring"""


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

        UpperCAmelCase_          =							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`.''')

        super().__init__(_snake_case					,						_snake_case)
        UpperCAmelCase_          =							self.image_processor







   def __call__(      self		:						List[Any]					,						_snake_case		:						Optional[ImageInput] = None					,						_snake_case		:						Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None					,						_snake_case		:						bool = True					,						_snake_case		:						Union[bool, str, PaddingStrategy] = False					,						_snake_case		:						Union[bool, str, TruncationStrategy] = False					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						int = 0					,						_snake_case		:						Optional[int] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						Optional[bool] = None					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = False					,						_snake_case		:						bool = True					,						_snake_case		:						Optional[Union[str, TensorType]] = None					,						**_snake_case		:						Any					,						):

        """simple docstring"""


        if text is None and images is None:
             raise ValueError('''You have to specify either text or images. Both cannot be none.''')

        if text is not None:
             UpperCAmelCase_          =							self.tokenizer(
                 text=_snake_case					,						add_special_tokens=_snake_case					,						padding=_snake_case					,						truncation=_snake_case					,						max_length=_snake_case					,						stride=_snake_case					,						pad_to_multiple_of=_snake_case					,						return_token_type_ids=_snake_case					,						return_attention_mask=_snake_case					,						return_overflowing_tokens=_snake_case					,						return_special_tokens_mask=_snake_case					,						return_offsets_mapping=_snake_case					,						return_length=_snake_case					,						verbose=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)
        if images is not None:
             UpperCAmelCase_          =							self.image_processor(
                 _snake_case					,						return_image_mask=_snake_case					,						return_codebook_pixels=_snake_case					,						return_tensors=_snake_case					,						**_snake_case					,						)

        if text is not None and images is not None:
             encoding.update(_snake_case)
             return encoding
        elif text is not None:
             return encoding
        else:
             return BatchEncoding(data=dict(**_snake_case)					,						tensor_type=_snake_case)







   def lowerCamelCase						(      self		:						Any					,						*_snake_case		:						Optional[Any]					,						**_snake_case		:						int):

        """simple docstring"""


        return self.tokenizer.batch_decode(*_snake_case					,						**_snake_case)







   def lowerCamelCase						(      self		:						Optional[int]					,						*_snake_case		:						int					,						**_snake_case		:						Dict):

        """simple docstring"""


        return self.tokenizer.decode(*_snake_case					,						**_snake_case)







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self.tokenizer.model_input_names
        UpperCAmelCase_          =							self.image_processor.model_input_names
        return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))







   @property
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''					,						_snake_case					,						)
        return self.image_processor_class







   @property
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        warnings.warn(
            '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''					,						_snake_case					,						)
        return self.image_processor






