

import unittest
from pathlib import Path
from shutil import copyfile

from transformers import SPIECE_UNDERLINE, is_sentencepiece_available
from transformers.models.speech_to_text import SpeechaTextTokenizer
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


lowercase_									=   get_tests_dir('fixtures/test_sentencepiece.model')

if is_sentencepiece_available():
  import sentencepiece as sp


lowercase_									=   5
lowercase_									=   1_0





@require_sentencepiece
@require_tokenizers
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE			,			unittest.TestCase							):
  _a									=  SpeechaTextTokenizer
  _a									=  False
  _a									=  True




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        super().setUp()

        _lowercase	       =sp.SentencePieceProcessor()
        spm_model.Load(lowerCAmelCase					)
        _lowercase	       =['<s>', '<pad>', '</s>', '<unk>']

        vocab += [spm_model.IdToPiece(id_					) for id_ in range(len(lowerCAmelCase					)					)]
        _lowercase	       =dict(zip(lowerCAmelCase							,   range(len(lowerCAmelCase					)					)					)					)

        _lowercase	       =Path(self.tmpdirname					)
        save_json(lowerCAmelCase							,   save_dir / VOCAB_FILES_NAMES['vocab_file']					)
        if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
              copyfile(lowerCAmelCase							,   save_dir / VOCAB_FILES_NAMES['spm_file']					)

        _lowercase	       =SpeechaTextTokenizer.from_pretrained(self.tmpdirname					)
        tokenizer.save_pretrained(self.tmpdirname					)




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        _lowercase	       ='<pad>'
        _lowercase	       =1

        self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase					)							,   lowerCAmelCase					)
        self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase					)							,   lowerCAmelCase					)




  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        _lowercase	       =list(self.get_tokenizer().get_vocab().keys()					)

        self.assertEqual(vocab_keys[0]							,   '<s>'					)
        self.assertEqual(vocab_keys[1]							,   '<pad>'					)
        self.assertEqual(vocab_keys[-1]							,   'j'					)
        self.assertEqual(len(lowerCAmelCase					)							,   1_001					)




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






        self.assertEqual(self.get_tokenizer().vocab_size							,   1_001					)




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






        _lowercase	       =SpeechaTextTokenizer.from_pretrained(self.tmpdirname					)

        _lowercase	       =tokenizer.tokenize('This is a test'					)
        self.assertListEqual(lowerCAmelCase							,   ['▁This', '▁is', '▁a', '▁t', 'est']					)

        self.assertListEqual(
            tokenizer.convert_tokens_to_ids(lowerCAmelCase					)							,   [289, 50, 14, 174, 386]							,   )

        _lowercase	       =tokenizer.tokenize('I was born in 92000, and this is falsé.'					)
        self.assertListEqual(
            lowerCAmelCase							,   [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.']							,   )
        _lowercase	       =tokenizer.convert_tokens_to_ids(lowerCAmelCase					)
        self.assertListEqual(lowerCAmelCase							,   [12, 25, 88, 59, 28, 23, 11, 4, 606, 351, 351, 351, 7, 16, 70, 50, 76, 84, 10, 4, 8]					)

        _lowercase	       =tokenizer.convert_ids_to_tokens(lowerCAmelCase					)
        self.assertListEqual(
            lowerCAmelCase							,   [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.']							,   )




  @slow
  def   A__     (				self					)  -> int:
        '''simple docstring'''






        _lowercase	       ={'input_ids': [[3_791, 797, 31, 11, 64, 797, 31, 2_429, 433, 12, 1_176, 12, 20, 786, 915, 142, 2_413, 240, 37, 3_238, 797, 31, 11, 35, 93, 915, 142, 2_413, 240, 37, 5_540, 567, 1_276, 93, 37, 610, 40, 62, 455, 657, 1_042, 123, 780, 177, 37, 309, 241, 1_298, 514, 20, 292, 2_737, 114, 2_469, 241, 85, 64, 302, 548, 528, 423, 4, 509, 406, 423, 37, 601, 4, 777, 302, 548, 528, 423, 284, 4, 3_388, 511, 459, 4, 3_555, 40, 321, 302, 705, 4, 3_388, 511, 583, 326, 5, 5, 5, 62, 3_310, 560, 177, 2_680, 217, 1_508, 32, 31, 853, 418, 64, 583, 511, 1_605, 62, 35, 93, 560, 177, 2_680, 217, 1_508, 1_521, 64, 583, 511, 519, 62, 20, 1_515, 764, 20, 149, 261, 5_625, 7_972, 20, 5_540, 567, 1_276, 93, 3_925, 1_675, 11, 15, 802, 7_972, 576, 217, 1_508, 11, 35, 93, 1_253, 2_441, 15, 289, 652, 31, 416, 321, 3_842, 115, 40, 911, 8, 476, 619, 4, 380, 142, 423, 335, 240, 35, 93, 264, 8, 11, 335, 569, 420, 163, 5, 2], [260, 548, 528, 423, 20, 451, 20, 2_681, 1_153, 3_434, 20, 5_540, 37, 567, 126, 1_253, 2_441, 3_376, 449, 210, 431, 1_563, 177, 767, 5_540, 11, 1_203, 472, 11, 2_953, 685, 285, 364, 706, 1_153, 20, 6_799, 20, 2_869, 20, 4_464, 126, 40, 2_429, 20, 1_040, 866, 2_664, 418, 20, 318, 20, 1_726, 186, 20, 265, 522, 35, 93, 2_191, 4_634, 20, 1_040, 12, 6_799, 15, 228, 2_356, 142, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
        # fmt: on

        self.tokenizer_integration_test_util(
            expected_encoding=lowerCAmelCase							,   model_name='facebook/s2t-small-mustc-en-de-st'							,   revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad'							,   )





@require_sentencepiece
class  __lowerCAmelCase     (					unittest.TestCase							):
  _a									=  """valhalla/s2t_mustc_multilinguial_medium"""

  _a									=  """C'est trop cool"""
  _a									=  """Esto es genial"""




  @classmethod
  def   A__     (				cls					)  -> int:
        '''simple docstring'''






        _lowercase	       =SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name					)
        return cls




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        self.assertEqual(self.tokenizer.lang_code_to_id['pt']							,   4					)
        self.assertEqual(self.tokenizer.lang_code_to_id['ru']							,   6					)
        self.assertEqual(self.tokenizer.lang_code_to_id['it']							,   9					)
        self.assertEqual(self.tokenizer.lang_code_to_id['de']							,   11					)




  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        self.assertEqual(self.tokenizer.vocab_size							,   10_000					)




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        self.assertIn(lowerCAmelCase							,   self.tokenizer.all_special_ids					)
        _lowercase	       =[ES_CODE, 4, 1_601, 47, 7_647, 2]
        _lowercase	       =self.tokenizer.decode(lowerCAmelCase							,   skip_special_tokens=lowerCAmelCase					)
        _lowercase	       =self.tokenizer.decode(generated_ids[1:]							,   skip_special_tokens=lowerCAmelCase					)
        self.assertEqual(lowerCAmelCase							,   lowerCAmelCase					)
        self.assertNotIn(self.tokenizer.eos_token							,   lowerCAmelCase					)




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






        _lowercase	       ='fr'
        _lowercase	       =self.tokenizer(self.french_text					).input_ids
        self.assertEqual(encoded[0]							,   lowerCAmelCase					)
        self.assertEqual(encoded[-1]							,   self.tokenizer.eos_token_id					)




  def   A__     (				self					)  -> List[Any]:
        '''simple docstring'''






        _lowercase	       ='fr'
        self.assertListEqual(self.tokenizer.prefix_tokens							,   [FR_CODE]					)

        _lowercase	       ='es'
        self.assertListEqual(self.tokenizer.prefix_tokens							,   [ES_CODE]					)





import logging

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,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


lowercase_									=   logging.getLogger(__name__)





class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase=None							,   lowerCAmelCase=None					)  -> List[str]:
        '''simple docstring'''






        _lowercase	       =self.layer[current_layer](lowerCAmelCase							,   lowerCAmelCase							,   head_mask[current_layer]					)

        _lowercase	       =layer_outputs[0]

        return hidden_states





@add_start_docstrings(
    """The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top."""			,			SCREAMING_SNAKE_CASE			,			)
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):




  def __init__(				self							,   lowerCAmelCase					)  -> Union[str, Any]:
        '''simple docstring'''






        super().__init__(lowerCAmelCase					)

        _lowercase	       =BertEncoderWithPabee(lowerCAmelCase					)

        self.init_weights()
        _lowercase	       =0
        _lowercase	       =0
        _lowercase	       =0

        _lowercase	       =0




  def   A__     (				self							,   lowerCAmelCase					)  -> Optional[Any]:
        '''simple docstring'''






        _lowercase	       =threshold




  def   A__     (				self							,   lowerCAmelCase					)  -> List[Any]:
        '''simple docstring'''






        _lowercase	       =patience




  def   A__     (				self					)  -> Dict:
        '''simple docstring'''






        _lowercase	       =0
        _lowercase	       =0




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        _lowercase	       =self.inference_layers_num / self.inference_instances_num
        _lowercase	       =(
            F'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ='''
            F''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***'''
        )
        print(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							,   lowerCAmelCase=None							,   lowerCAmelCase=None							,   lowerCAmelCase=False							,   )  -> str:
        '''simple docstring'''






        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:
              _lowercase	       =input_ids.size()
        elif inputs_embeds is not None:
              _lowercase	       =inputs_embeds.size()[:-1]
        else:
              raise ValueError('You have to specify either input_ids or inputs_embeds'					)

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

        if attention_mask is None:
              _lowercase	       =torch.ones(lowerCAmelCase							,   device=lowerCAmelCase					)
        if token_type_ids is None:
              _lowercase	       =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.
        _lowercase	       =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 self.config.is_decoder and encoder_hidden_states is not None:
              _lowercase       ,       _lowercase       ,       _lowercase	       =encoder_hidden_states.size()
              _lowercase	       =(encoder_batch_size, encoder_sequence_length)
              if encoder_attention_mask is None:
                    _lowercase	       =torch.ones(lowerCAmelCase							,   device=lowerCAmelCase					)
              _lowercase	       =self.invert_attention_mask(lowerCAmelCase					)
        else:
              _lowercase	       =None

        # 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]
        _lowercase	       =self.get_head_mask(lowerCAmelCase							,   self.config.num_hidden_layers					)

        _lowercase	       =self.embeddings(
            input_ids=lowerCAmelCase							,   position_ids=lowerCAmelCase							,   token_type_ids=lowerCAmelCase							,   inputs_embeds=lowerCAmelCase					)
        _lowercase	       =embedding_output

        if self.training:
              _lowercase	       =[]
              for i in range(self.config.num_hidden_layers					):
                    _lowercase	       =self.encoder.adaptive_forward(
                        lowerCAmelCase							,   current_layer=lowerCAmelCase							,   attention_mask=lowerCAmelCase							,   head_mask=lowerCAmelCase					)

                    _lowercase	       =self.pooler(lowerCAmelCase					)
                    _lowercase	       =output_layers[i](output_dropout(lowerCAmelCase					)					)
                    res.append(lowerCAmelCase					)
        elif self.patience == 0:  # Use all layers for inference
              _lowercase	       =self.encoder(
                  lowerCAmelCase							,   attention_mask=lowerCAmelCase							,   head_mask=lowerCAmelCase							,   encoder_hidden_states=lowerCAmelCase							,   encoder_attention_mask=lowerCAmelCase							,   )
              _lowercase	       =self.pooler(encoder_outputs[0]					)
              _lowercase	       =[output_layers[self.config.num_hidden_layers - 1](lowerCAmelCase					)]
        else:
              _lowercase	       =0
              _lowercase	       =None
              _lowercase	       =0
              for i in range(self.config.num_hidden_layers					):
                    calculated_layer_num += 1
                    _lowercase	       =self.encoder.adaptive_forward(
                        lowerCAmelCase							,   current_layer=lowerCAmelCase							,   attention_mask=lowerCAmelCase							,   head_mask=lowerCAmelCase					)

                    _lowercase	       =self.pooler(lowerCAmelCase					)
                    _lowercase	       =output_layers[i](lowerCAmelCase					)
                    if regression:
                          _lowercase	       =logits.detach()
                          if patient_result is not None:
                                _lowercase	       =patient_result.detach()
                          if (patient_result is not None) and torch.abs(patient_result - labels					) < self.regression_threshold:
                                patient_counter += 1
                          else:
                                _lowercase	       =0
                    else:
                          _lowercase	       =logits.detach().argmax(dim=1					)
                          if patient_result is not None:
                                _lowercase	       =patient_result.detach().argmax(dim=1					)
                          if (patient_result is not None) and torch.all(labels.eq(lowerCAmelCase					)					):
                                patient_counter += 1
                          else:
                                _lowercase	       =0

                    _lowercase	       =logits
                    if patient_counter == self.patience:
                          break
              _lowercase	       =[patient_result]
              self.inference_layers_num += calculated_layer_num
              self.inference_instances_num += 1

        return res





@add_start_docstrings(
    """Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of
    the pooled output) e.g. for GLUE tasks. """			,			SCREAMING_SNAKE_CASE			,			)
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE							):




  def __init__(				self							,   lowerCAmelCase					)  -> List[Any]:
        '''simple docstring'''






        super().__init__(lowerCAmelCase					)
        _lowercase	       =config.num_labels

        _lowercase	       =BertModelWithPabee(lowerCAmelCase					)
        _lowercase	       =nn.Dropout(config.hidden_dropout_prob					)
        _lowercase	       =nn.ModuleList(
            [nn.Linear(config.hidden_size							,   self.config.num_labels					) for _ in range(config.num_hidden_layers					)]					)

        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							,   )  -> Union[str, Any]:
        '''simple docstring'''






        _lowercase	       =self.bert(
            input_ids=lowerCAmelCase							,   attention_mask=lowerCAmelCase							,   token_type_ids=lowerCAmelCase							,   position_ids=lowerCAmelCase							,   head_mask=lowerCAmelCase							,   inputs_embeds=lowerCAmelCase							,   output_dropout=self.dropout							,   output_layers=self.classifiers							,   regression=self.num_labels == 1							,   )

        _lowercase	       =(logits[-1],)

        if labels is not None:
              _lowercase	       =None
              _lowercase	       =0
              for ix, logits_item in enumerate(lowerCAmelCase					):
                    if self.num_labels == 1:
                          #  We are doing regression
                          _lowercase	       =MSELoss()
                          _lowercase	       =loss_fct(logits_item.view(-1					)							,   labels.view(-1					)					)
                    else:
                          _lowercase	       =CrossEntropyLoss()
                          _lowercase	       =loss_fct(logits_item.view(-1							,   self.num_labels					)							,   labels.view(-1					)					)
                    if total_loss is None:
                          _lowercase	       =loss
                    else:
                          total_loss += loss * (ix + 1)
                    total_weights += ix + 1
              _lowercase	       =(total_loss / total_weights,) + outputs

        return outputs


