





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). "       ,				__SCREAMING_SNAKE_CASE       ,				)
class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''
 lowercase_						=     RobertaConfig
 lowercase_						=     "roberta"

 def __init__(self							:  List[Any]			,					UpperCAmelCase_							:  Union[str, Any])			->Union[str, Any]:



   '''simple docstring'''



   super().__init__(UpperCAmelCase_)

   lowerCamelCase__: Any         =RobertaEmbeddings(UpperCAmelCase_)
   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. "       ,				__SCREAMING_SNAKE_CASE       ,				)
class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''
 lowercase_						=     RobertaConfig
 lowercase_						=     "roberta"

 def __init__(self							:  Optional[Any]			,					UpperCAmelCase_							:  List[str])			->str:



   '''simple docstring'''



   super().__init__(UpperCAmelCase_)
   lowerCamelCase__: Union[str, Any]         =config.num_labels
   lowerCamelCase__: Union[str, Any]         =config.num_hidden_layers

   lowerCamelCase__: Dict         =DeeRobertaModel(UpperCAmelCase_)
   lowerCamelCase__: Optional[Any]         =nn.Dropout(config.hidden_dropout_prob)
   lowerCamelCase__: Tuple         =nn.Linear(config.hidden_size			,					self.config.num_labels)







 @add_start_docstrings_to_model_forward(UpperCAmelCase_)
 def 				SCREAMING_SNAKE_CASE_   (self							:  Dict			,					UpperCAmelCase_							:  Dict=None			,					UpperCAmelCase_							:  Tuple=None			,					UpperCAmelCase_							:  Dict=None			,					UpperCAmelCase_							:  Optional[int]=None			,					UpperCAmelCase_							:  Optional[int]=None			,					UpperCAmelCase_							:  int=None			,					UpperCAmelCase_							:  Any=None			,					UpperCAmelCase_							:  Dict=-1			,					UpperCAmelCase_							:  List[Any]=False			,					)			->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__: List[Any]         =self.num_layers
   try:
     lowerCamelCase__: Any         =self.roberta(
         UpperCAmelCase_			,					attention_mask=UpperCAmelCase_			,					token_type_ids=UpperCAmelCase_			,					position_ids=UpperCAmelCase_			,					head_mask=UpperCAmelCase_			,					inputs_embeds=UpperCAmelCase_			,					)

     lowerCamelCase__: int         =outputs[1]

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

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

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

     if train_highway:
       lowerCamelCase__: Optional[Any]         =(sum(highway_losses[:-1]),) + outputs
       # exclude the final highway, of course
     else:
       lowerCamelCase__: Any         =(loss,) + outputs
   if not self.training:
     lowerCamelCase__: Any         =outputs + ((original_entropy, highway_entropy), exit_layer)
     if output_layer >= 0:
       lowerCamelCase__: Tuple         =(
           (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'''




from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)

