"""simple docstring"""



import os
import re
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE__:Dict			=	logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__:Optional[Any]			=	{"""vocab_file""": """spiece.model"""}

SCREAMING_SNAKE_CASE__:Optional[Any]			=	{
    """vocab_file""": {
        """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""",
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model"""
        ),
    }
}

SCREAMING_SNAKE_CASE__:str			=	{
    """google/bigbird-roberta-base""": 4096,
    """google/bigbird-roberta-large""": 4096,
    """google/bigbird-base-trivia-itc""": 4096,
}






class 				snake_case__     (   snake_case_   ):
 _snake_case   :			List[str]           =		VOCAB_FILES_NAMES
 _snake_case   :			List[Any]           =		PRETRAINED_VOCAB_FILES_MAP
 _snake_case   :			str           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _snake_case   :			int           =		["""input_ids""", """attention_mask"""]
 _snake_case   :			List[int]           =		[]


 def __init__(				self  ,						lowerCamelCase  ,						lowerCamelCase="<unk>"  ,						lowerCamelCase="<s>"  ,						lowerCamelCase="</s>"  ,						lowerCamelCase="<pad>"  ,						lowerCamelCase="[SEP]"  ,						lowerCamelCase="[MASK]"  ,						lowerCamelCase="[CLS]"  ,						lowerCamelCase = None  ,						**lowerCamelCase  ,						):
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else bos_token
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else eos_token
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else unk_token
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else pad_token
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else cls_token
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else sep_token

        # Mask token behave like a normal word, i.e. include the space before it
        __a     				=  AddedToken(lowerCamelCase  ,						lstrip=lowerCamelCase  ,						rstrip=lowerCamelCase		) if isinstance(lowerCamelCase  ,						lowerCamelCase		) else mask_token

        __a     				=  {} if sp_model_kwargs is None else sp_model_kwargs

        super().__init__(
            bos_token=lowerCamelCase  ,						eos_token=lowerCamelCase  ,						unk_token=lowerCamelCase  ,						pad_token=lowerCamelCase  ,						sep_token=lowerCamelCase  ,						mask_token=lowerCamelCase  ,						cls_token=lowerCamelCase  ,						sp_model_kwargs=self.sp_model_kwargs  ,						**lowerCamelCase  ,						)

        __a     				=  vocab_file

        __a     				=  spm.SentencePieceProcessor(**self.sp_model_kwargs		)
        self.sp_model.Load(lowerCamelCase		)


 @property
 def 		a__ (				self		):
        return self.sp_model.get_piece_size()


 def 		a__ (				self		):
        __a     				=  {self.convert_ids_to_tokens(lowerCamelCase		): i for i in range(self.vocab_size		)}
        vocab.update(self.added_tokens_encoder		)
        return vocab


 def __getstate__(				self		):
        __a     				=  self.__dict__.copy()
        __a     				=  None
        return state


 def __setstate__(				self  ,						lowerCamelCase		):
        __a     				=  d

        # for backward compatibility
        if not hasattr(self  ,						"sp_model_kwargs"		):
               __a     				=  {}

        __a     				=  spm.SentencePieceProcessor(**self.sp_model_kwargs		)
        self.sp_model.Load(self.vocab_file		)


 def 		a__ (				self  ,						lowerCamelCase		):
        return self.sp_model.encode(lowerCamelCase  ,						out_type=lowerCamelCase		)


 def 		a__ (				self  ,						lowerCamelCase		):
        return self.sp_model.piece_to_id(lowerCamelCase		)


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  self.sp_model.IdToPiece(lowerCamelCase		)
        return token


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  []
        __a     				=  ""
        __a     				=  False
        for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                      if not prev_is_special:
                             out_string += " "
                      out_string += self.sp_model.decode(lowerCamelCase		) + token
                      __a     				=  True
                      __a     				=  []
               else:
                      current_sub_tokens.append(lowerCamelCase		)
                      __a     				=  False
        out_string += self.sp_model.decode(lowerCamelCase		)
        return out_string.strip()


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = False  ,						lowerCamelCase = None  ,						lowerCamelCase = True  ,						**lowerCamelCase  ,						):
        __a     				=  kwargs.pop("use_source_tokenizer"  ,						lowerCamelCase		)

        __a     				=  self.convert_ids_to_tokens(lowerCamelCase  ,						skip_special_tokens=lowerCamelCase		)

        # To avoid mixing byte-level and unicode for byte-level BPT
        # we need to build string separately for added tokens and byte-level tokens
        # cf. https://github.com/huggingface/transformers/issues/1133
        __a     				=  []
        __a     				=  []
        for token in filtered_tokens:
               if skip_special_tokens and token in self.all_special_ids:
                      continue
               if token in self.added_tokens_encoder:
                      if current_sub_text:
                             sub_texts.append(self.convert_tokens_to_string(lowerCamelCase		)		)
                             __a     				=  []
                      sub_texts.append(lowerCamelCase		)
               else:
                      current_sub_text.append(lowerCamelCase		)
        if current_sub_text:
               sub_texts.append(self.convert_tokens_to_string(lowerCamelCase		)		)

        # Mimic the behavior of the Rust tokenizer:
        # No space before [MASK] and [SEP]
        if spaces_between_special_tokens:
               __a     				=  re.sub(R" (\[(MASK|SEP)\])"  ,						R"\1"  ,						" ".join(lowerCamelCase		)		)
        else:
               __a     				=  "".join(lowerCamelCase		)

        __a     				=  (
            clean_up_tokenization_spaces
            if clean_up_tokenization_spaces is not None
            else self.clean_up_tokenization_spaces
        )
        if clean_up_tokenization_spaces:
               __a     				=  self.clean_up_tokenization(lowerCamelCase		)
               return clean_text
        else:
               return text


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None		):
        if not os.path.isdir(lowerCamelCase		):
               logger.error(F"Vocabulary path ({save_directory}) should be a directory"		)
               return
        __a     				=  os.path.join(
            lowerCamelCase  ,						(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)

        if os.path.abspath(self.vocab_file		) != os.path.abspath(lowerCamelCase		) and os.path.isfile(self.vocab_file		):
               copyfile(self.vocab_file  ,						lowerCamelCase		)
        elif not os.path.isfile(self.vocab_file		):
               with open(lowerCamelCase  ,						"wb"		) as fi:
                      __a     				=  self.sp_model.serialized_model_proto()
                      fi.write(lowerCamelCase		)

        return (out_vocab_file,)


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None		):
        if token_ids_a is None:
               return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        __a     				=  [self.cls_token_id]
        __a     				=  [self.sep_token_id]
        return cls + token_ids_a + sep + token_ids_a + sep


 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None  ,						lowerCamelCase = False		):
        if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=lowerCamelCase  ,						token_ids_a=lowerCamelCase  ,						already_has_special_tokens=lowerCamelCase		)

        if token_ids_a is None:
               return [1] + ([0] * len(lowerCamelCase		)) + [1]
        return [1] + ([0] * len(lowerCamelCase		)) + [1] + ([0] * len(lowerCamelCase		)) + [1]






 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase = None		):
        __a     				=  [self.sep_token_id]
        __a     				=  [self.cls_token_id]
        if token_ids_a is None:
               return len(cls + token_ids_a + sep		) * [0]
        return len(cls + token_ids_a + sep		) * [0] + len(token_ids_a + sep		) * [1]

"""simple docstring"""



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

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEmbeddings,
    BertLayer,
    BertPooler,
    BertPreTrainedModel,
)



def 					_lowerCamelCase(					a							):
       __a     				=  torch.exp(a							)
       __a     				=  torch.sum(a ,  dim=1							)  # sum of exp(x_i)
       __a     				=  torch.sum(x * exp_x ,  dim=1							)  # sum of x_i * exp(x_i)
       return torch.log(a							) - B / A






class 				snake_case__     (   nn.Module   ):


 def __init__(				self  ,						lowerCamelCase		):
        super().__init__()
        __a     				=  config.output_attentions
        __a     				=  config.output_hidden_states
        __a     				=  nn.ModuleList([BertLayer(lowerCamelCase		) for _ in range(config.num_hidden_layers		)]		)
        __a     				=  nn.ModuleList([BertHighway(lowerCamelCase		) for _ in range(config.num_hidden_layers		)]		)

        __a     				=  [-1 for _ in range(config.num_hidden_layers		)]


 def 		a__ (				self  ,						lowerCamelCase		):
        if (type(lowerCamelCase		) is float) or (type(lowerCamelCase		) is int):
               for i in range(len(self.early_exit_entropy		)		):
                      __a     				=  x
        else:
               __a     				=  x


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  pooler.state_dict()
        for highway in self.highway:
               for name, param in highway.pooler.state_dict().items():
                      param.copy_(loaded_model[name]		)






 def 		a__ (				self  ,						lowerCamelCase  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						):
        __a     				=  ()
        __a     				=  ()
        __a     				=  ()
        for i, layer_module in enumerate(self.layer		):
               if self.output_hidden_states:
                      __a     				=  all_hidden_states + (hidden_states,)

               __a     				=  layer_module(
                   lowerCamelCase  ,						lowerCamelCase  ,						head_mask[i]  ,						lowerCamelCase  ,						lowerCamelCase		)
               __a     				=  layer_outputs[0]

               if self.output_attentions:
                      __a     				=  all_attentions + (layer_outputs[1],)

               __a     				=  (hidden_states,)
               if self.output_hidden_states:
                      __a     				=  current_outputs + (all_hidden_states,)
               if self.output_attentions:
                      __a     				=  current_outputs + (all_attentions,)

               __a     				=  self.highway[i](lowerCamelCase		)
               # logits, pooled_output

               if not self.training:
                      __a     				=  highway_exit[0]
                      __a     				=  entropy(lowerCamelCase		)
                      __a     				=  highway_exit + (highway_entropy,)  # logits, hidden_states(?), entropy
                      __a     				=  all_highway_exits + (highway_exit,)

                      if highway_entropy < self.early_exit_entropy[i]:
                             __a     				=  (highway_logits,) + current_outputs[1:] + (all_highway_exits,)
                             raise HighwayException(lowerCamelCase  ,						i + 1		)
               else:
                      __a     				=  all_highway_exits + (highway_exit,)

        # Add last layer
        if self.output_hidden_states:
               __a     				=  all_hidden_states + (hidden_states,)

        __a     				=  (hidden_states,)
        if self.output_hidden_states:
               __a     				=  outputs + (all_hidden_states,)
        if self.output_attentions:
               __a     				=  outputs + (all_attentions,)

        __a     				=  outputs + (all_highway_exits,)
        return outputs  # last-layer hidden state, (all hidden states), (all attentions), all highway exits






@add_start_docstrings(
    """The Bert Model transformer with early exiting (DeeBERT). """,		snake_case_,		)
class 				snake_case__     (   snake_case_   ):


 def __init__(				self  ,						lowerCamelCase		):
        super().__init__(lowerCamelCase		)
        __a     				=  config

        __a     				=  BertEmbeddings(lowerCamelCase		)
        __a     				=  DeeBertEncoder(lowerCamelCase		)
        __a     				=  BertPooler(lowerCamelCase		)

        self.init_weights()


 def 		a__ (				self		):
        self.encoder.init_highway_pooler(self.pooler		)


 def 		a__ (				self		):
        return self.embeddings.word_embeddings


 def 		a__ (				self  ,						lowerCamelCase		):
        __a     				=  value


 def 		a__ (				self  ,						lowerCamelCase		):
        for layer, heads in heads_to_prune.items():
               self.encoder.layer[layer].attention.prune_heads(lowerCamelCase		)






 @add_start_docstrings_to_model_forward(lowerCamelCase		)
 def 		a__ (				self  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						):
        if input_ids is not None and inputs_embeds is not None:
               raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time"		)
        elif input_ids is not None:
               __a     				=  input_ids.size()
        elif inputs_embeds is not None:
               __a     				=  inputs_embeds.size()[:-1]
        else:
               raise ValueError("You have to specify either input_ids or inputs_embeds"		)

        __a     				=  input_ids.device if input_ids is not None else inputs_embeds.device

        if attention_mask is None:
               __a     				=  torch.ones(lowerCamelCase  ,						device=lowerCamelCase		)
        if encoder_attention_mask is None:
               __a     				=  torch.ones(lowerCamelCase  ,						device=lowerCamelCase		)
        if token_type_ids is None:
               __a     				=  torch.zeros(lowerCamelCase  ,						dtype=torch.long  ,						device=lowerCamelCase		)

        # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
        # ourselves in which case we just need to make it broadcastable to all heads.
        __a     				=  self.get_extended_attention_mask(lowerCamelCase  ,						lowerCamelCase  ,						lowerCamelCase		)

        # If a 2D ou 3D attention mask is provided for the cross-attention
        # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
        if encoder_attention_mask.dim() == 3:
               __a     				=  encoder_attention_mask[:, None, :, :]
        if encoder_attention_mask.dim() == 2:
               __a     				=  encoder_attention_mask[:, None, None, :]

        __a     				=  encoder_extended_attention_mask.to(
            dtype=next(self.parameters()		).dtype		)  # fp16 compatibility
        __a     				=  (1.0 - encoder_extended_attention_mask) * -1_0000.0

        # Prepare head mask if needed
        # 1.0 in head_mask indicate we keep the head
        # attention_probs has shape bsz x n_heads x N x N
        # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
        # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
        __a     				=  self.get_head_mask(lowerCamelCase  ,						self.config.num_hidden_layers		)

        __a     				=  self.embeddings(
            input_ids=lowerCamelCase  ,						position_ids=lowerCamelCase  ,						token_type_ids=lowerCamelCase  ,						inputs_embeds=lowerCamelCase		)
        __a     				=  self.encoder(
            lowerCamelCase  ,						attention_mask=lowerCamelCase  ,						head_mask=lowerCamelCase  ,						encoder_hidden_states=lowerCamelCase  ,						encoder_attention_mask=lowerCamelCase  ,						)
        __a     				=  encoder_outputs[0]
        __a     				=  self.pooler(lowerCamelCase		)

        __a     				=  (
            sequence_output,
            pooled_output,
        ) + encoder_outputs[
            1:
        ]  # add hidden_states and attentions if they are here
        return outputs  # sequence_output, pooled_output, (hidden_states), (attentions), highway exits






class 				snake_case__     (   snake_case_   ):


 def __init__(				self  ,						lowerCamelCase  ,						lowerCamelCase		):
        __a     				=  message
        __a     				=  exit_layer  # start from 1!






class 				snake_case__     (   nn.Module   ):


 def __init__(				self  ,						lowerCamelCase		):
        super().__init__()
        __a     				=  BertPooler(lowerCamelCase		)
        __a     				=  nn.Dropout(config.hidden_dropout_prob		)
        __a     				=  nn.Linear(config.hidden_size  ,						config.num_labels		)






 def 		a__ (				self  ,						lowerCamelCase		):
        # Pooler
        __a     				=  encoder_outputs[0]
        __a     				=  self.pooler(lowerCamelCase		)
        # "return" pooler_output

        # BertModel
        __a     				=  (pooler_input, pooler_output) + encoder_outputs[1:]
        # "return" bmodel_output

        # Dropout and classification
        __a     				=  bmodel_output[1]

        __a     				=  self.dropout(lowerCamelCase		)
        __a     				=  self.classifier(lowerCamelCase		)

        return logits, pooled_output






@add_start_docstrings(
    """Bert Model (with early exiting - DeeBERT) with a classifier on top,
    also takes care of multi-layer training. """,		snake_case_,		)
class 				snake_case__     (   snake_case_   ):


 def __init__(				self  ,						lowerCamelCase		):
        super().__init__(lowerCamelCase		)
        __a     				=  config.num_labels
        __a     				=  config.num_hidden_layers

        __a     				=  DeeBertModel(lowerCamelCase		)
        __a     				=  nn.Dropout(config.hidden_dropout_prob		)
        __a     				=  nn.Linear(config.hidden_size  ,						self.config.num_labels		)

        self.init_weights()






 @add_start_docstrings_to_model_forward(lowerCamelCase		)
 def 		a__ (				self  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=None  ,						lowerCamelCase=-1  ,						lowerCamelCase=False  ,						):
        __a     				=  self.num_layers
        try:
               __a     				=  self.bert(
                   lowerCamelCase  ,						attention_mask=lowerCamelCase  ,						token_type_ids=lowerCamelCase  ,						position_ids=lowerCamelCase  ,						head_mask=lowerCamelCase  ,						inputs_embeds=lowerCamelCase  ,						)
               # sequence_output, pooled_output, (hidden_states), (attentions), highway exits

               __a     				=  outputs[1]

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

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

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

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

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