



"""simple docstring"""







import unittest

from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


lowercase__		:    Any				   =     get_tests_dir("""fixtures/test_sentencepiece.model""")







@require_sentencepiece
@require_tokenizers
class 				UpperCamelCase__       (     lowercase_, unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					ReformerTokenizer
      _SCREAMING_SNAKE_CASE      =					ReformerTokenizerFast
      _SCREAMING_SNAKE_CASE      =					True
      _SCREAMING_SNAKE_CASE      =					False
      _SCREAMING_SNAKE_CASE      =					True



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        super().setUp()

        lowerCAmelCase_       :    List[Any]								=			ReformerTokenizer(SCREAMING_SNAKE_CASE_   ,      keep_accents=SCREAMING_SNAKE_CASE_	)
        tokenizer.save_pretrained(self.tmpdirname	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    Union[str, Any]								=			'<s>'
        lowerCAmelCase_       :    Tuple								=			1

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



      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        lowerCAmelCase_       :    Optional[int]								=			list(self.get_tokenizer().get_vocab().keys()	)

        self.assertEqual(vocab_keys[0]   ,      '<unk>'	)
        self.assertEqual(vocab_keys[1]   ,      '<s>'	)
        self.assertEqual(vocab_keys[-1]   ,      'j'	)
        self.assertEqual(len(SCREAMING_SNAKE_CASE_	)   ,      1_0_0_0	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        self.assertEqual(self.get_tokenizer().vocab_size   ,      1_0_0_0	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        if not self.test_rust_tokenizer:
          return

        lowerCAmelCase_       :    List[str]								=			self.get_tokenizer()
        lowerCAmelCase_       :    List[Any]								=			self.get_rust_tokenizer()

        lowerCAmelCase_       :    Optional[Any]								=			'I was born in 92000, and this is falsé.'

        lowerCAmelCase_       :    int								=			tokenizer.tokenize(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Union[str, Any]								=			rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE_	)
        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    str								=			tokenizer.encode(SCREAMING_SNAKE_CASE_   ,      add_special_tokens=SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Union[str, Any]								=			rust_tokenizer.encode(SCREAMING_SNAKE_CASE_   ,      add_special_tokens=SCREAMING_SNAKE_CASE_	)
        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    List[str]								=			self.get_rust_tokenizer()
        lowerCAmelCase_       :    Tuple								=			tokenizer.encode(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    int								=			rust_tokenizer.encode(SCREAMING_SNAKE_CASE_	)
        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				str=1_5	):
        for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
          with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"	):
            lowerCAmelCase_       :    str								=			self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_   ,      **SCREAMING_SNAKE_CASE_	)

            # Simple input
            lowerCAmelCase_       :    Optional[int]								=			'This is a simple input'
            lowerCAmelCase_       :    Optional[Any]								=			['This is a simple input 1', 'This is a simple input 2']
            lowerCAmelCase_       :    Any								=			('This is a simple input', 'This is a pair')
            lowerCAmelCase_       :    List[Any]								=			[
                ('This is a simple input 1', 'This is a simple input 2'),
                ('This is a simple pair 1', 'This is a simple pair 2'),
            ]

            # Simple input tests
            self.assertRaises(SCREAMING_SNAKE_CASE_   ,      tokenizer_r.encode   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'	)

            # Simple input
            self.assertRaises(SCREAMING_SNAKE_CASE_   ,      tokenizer_r.encode_plus   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'	)

            # Simple input
            self.assertRaises(
                SCREAMING_SNAKE_CASE_   ,      tokenizer_r.batch_encode_plus   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'   ,      )

            # Pair input
            self.assertRaises(SCREAMING_SNAKE_CASE_   ,      tokenizer_r.encode   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'	)

            # Pair input
            self.assertRaises(SCREAMING_SNAKE_CASE_   ,      tokenizer_r.encode_plus   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'	)

            # Pair input
            self.assertRaises(
                SCREAMING_SNAKE_CASE_   ,      tokenizer_r.batch_encode_plus   ,      SCREAMING_SNAKE_CASE_   ,      max_length=SCREAMING_SNAKE_CASE_   ,      padding='max_length'   ,      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        pass



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    Tuple								=			ReformerTokenizer(SCREAMING_SNAKE_CASE_   ,      keep_accents=SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Dict								=			tokenizer.tokenize('This is a test'	)
        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      ['▁This', '▁is', '▁a', '▁t', 'est']	)

        self.assertListEqual(
            tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)   ,      [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]   ,      )

        lowerCAmelCase_       :    List[Any]								=			tokenizer.tokenize('I was born in 92000, and this is falsé.'	)
        self.assertListEqual(
            SCREAMING_SNAKE_CASE_   ,      [
                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',
                'é',
                '.',
            ]   ,      )
        lowerCAmelCase_       :    int								=			tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_	)
        self.assertListEqual(
            SCREAMING_SNAKE_CASE_   ,      [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4]   ,      )

        lowerCAmelCase_       :    Optional[int]								=			tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_	)
        self.assertListEqual(
            SCREAMING_SNAKE_CASE_   ,      [
                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>',
                '.',
            ]   ,      )



      @cached_property
      def 					SCREAMING_SNAKE_CASE__			(				self    :				str	):
        return ReformerTokenizer.from_pretrained('google/reformer-crime-and-punishment'	)



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        lowerCAmelCase_       :    List[str]								=			'Hello World!'
        lowerCAmelCase_       :    Optional[Any]								=			[1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7]

        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      self.big_tokenizer.encode(SCREAMING_SNAKE_CASE_	)	)



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    Dict								=			(
            'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
            ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'
        )
        lowerCAmelCase_       :    Dict								=			[
            1_0_8,
            2_6_5,
            2_4,
            1_1_1,
            4,
            2_5_8,
            1_5_6,
            3_5,
            2_8,
            2_7_5,
            3,
            2_5_9,
            2_9_7,
            2_6_0,
            8_4,
            4,
            3_5,
            1_1_0,
            4_4,
            8,
            2_5_9,
            9_1,
            2_6_8,
            2_1,
            1_1,
            2_0_9,
            2_7_4,
            1_0_9,
            2_6_6,
            2_7_7,
            1_1_7,
            8_6,
            9_3,
            3_1_5,
            2_5_8,
            2_7_8,
            2_5_8,
            2_7_7,
            2_5_8,
            0,
            2_5_8,
            2_8_8,
            2_5_8,
            3_1_9,
            2_5_8,
            0,
            2_5_8,
            0,
            2_5_8,
            0,
            2_5_8,
            0,
            2_5_8,
            2_8_7,
            2_5_8,
            3_1_5,
            2_5_8,
            2_8_9,
            2_5_8,
            2_7_8,
            9_9,
            2_6_9,
            2_6_6,
            2_6_2,
            8,
            2_5_9,
            2_4_1,
            4,
            2_1_7,
            2_3_0,
            2_6_8,
            2_6_6,
            5_5,
            1_6_8,
            1_0_6,
            7_5,
            1_9_3,
            2_6_6,
            2_2_3,
            2_7,
            4_9,
            2_6,
            2_8_2,
            2_5,
            2_6_4,
            2_9_9,
            1_9,
            2_6,
            0,
            2_5_8,
            2_7_7,
            1_1_7,
            8_6,
            9_3,
            1_7_6,
            1_8_3,
            2_7_0,
            1_1,
            2_6_2,
            4_2,
            6_1,
            2_6_5,
        ]

        self.assertListEqual(SCREAMING_SNAKE_CASE_   ,      self.big_tokenizer.encode(SCREAMING_SNAKE_CASE_	)	)



      @require_torch
      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        import torch

        from transformers import ReformerConfig, ReformerModel

        # Build sequence
        lowerCAmelCase_       :    List[Any]								=			list(self.big_tokenizer.get_vocab().keys()	)[:1_0]
        lowerCAmelCase_       :    Union[str, Any]								=			' '.join(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Tuple								=			self.big_tokenizer.encode_plus(SCREAMING_SNAKE_CASE_   ,      return_tensors='pt'	)
        lowerCAmelCase_       :    Optional[int]								=			self.big_tokenizer.batch_encode_plus([sequence, sequence]   ,      return_tensors='pt'	)

        lowerCAmelCase_       :    str								=			ReformerConfig()
        # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
        lowerCAmelCase_       :    int								=			encoded_sequence['input_ids'].shape
        lowerCAmelCase_       :    List[Any]								=			ReformerModel(SCREAMING_SNAKE_CASE_	)

        # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
        assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size

        with torch.no_grad():
          model(**SCREAMING_SNAKE_CASE_	)
          model(**SCREAMING_SNAKE_CASE_	)





      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        # fmt: off
        lowerCAmelCase_       :    int								=			{'input_ids': [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
        # fmt: on

        # This tokenizer does not know some characters like ")".
        # That is the reason why we use very simple texts here.
        # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
        lowerCAmelCase_       :    int								=			[
            'This is a very simple sentence.',
            'The quick brown fox jumps over the lazy dog.',
        ]

        self.tokenizer_integration_test_util(
            expected_encoding=SCREAMING_SNAKE_CASE_   ,      model_name='google/reformer-crime-and-punishment'   ,      revision='0e6c3decb8211d49bf881013425dc8b0448b3f5a'   ,      padding=SCREAMING_SNAKE_CASE_   ,      sequences=SCREAMING_SNAKE_CASE_   ,      )










"""simple docstring"""







import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         FlaubertForMultipleChoice,
         FlaubertForQuestionAnswering,
         FlaubertForQuestionAnsweringSimple,
         FlaubertForSequenceClassification,
         FlaubertForTokenClassification,
         FlaubertModel,
         FlaubertWithLMHeadModel,
     )
     from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST







class 				UpperCamelCase__       (     lowercase_  ):




      """simple docstring"""




      def __init__(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=1_3   ,      SCREAMING_SNAKE_CASE_    :				Dict=7   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				Dict=True   ,      SCREAMING_SNAKE_CASE_    :				List[str]=True   ,      SCREAMING_SNAKE_CASE_    :				str=False   ,      SCREAMING_SNAKE_CASE_    :				str=False   ,      SCREAMING_SNAKE_CASE_    :				Any=False   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=2   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=9_9   ,      SCREAMING_SNAKE_CASE_    :				Dict=0   ,      SCREAMING_SNAKE_CASE_    :				int=3_2   ,      SCREAMING_SNAKE_CASE_    :				Dict=5   ,      SCREAMING_SNAKE_CASE_    :				Dict=4   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				List[Any]=0.1   ,      SCREAMING_SNAKE_CASE_    :				List[str]=5_1_2   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=1_2   ,      SCREAMING_SNAKE_CASE_    :				Tuple=2   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=0.02   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]=3   ,      SCREAMING_SNAKE_CASE_    :				int=4   ,      SCREAMING_SNAKE_CASE_    :				List[Any]="last"   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]=None   ,      SCREAMING_SNAKE_CASE_    :				str=None   ,      ):
        lowerCAmelCase_       :    Tuple								=			parent
        lowerCAmelCase_       :    Tuple								=			batch_size
        lowerCAmelCase_       :    str								=			seq_length
        lowerCAmelCase_       :    List[Any]								=			is_training
        lowerCAmelCase_       :    Optional[int]								=			use_input_lengths
        lowerCAmelCase_       :    Union[str, Any]								=			use_token_type_ids
        lowerCAmelCase_       :    str								=			use_labels
        lowerCAmelCase_       :    str								=			gelu_activation
        lowerCAmelCase_       :    str								=			sinusoidal_embeddings
        lowerCAmelCase_       :    List[Any]								=			causal
        lowerCAmelCase_       :    Union[str, Any]								=			asm
        lowerCAmelCase_       :    Union[str, Any]								=			n_langs
        lowerCAmelCase_       :    Optional[Any]								=			vocab_size
        lowerCAmelCase_       :    Any								=			n_special
        lowerCAmelCase_       :    Union[str, Any]								=			hidden_size
        lowerCAmelCase_       :    str								=			num_hidden_layers
        lowerCAmelCase_       :    Tuple								=			num_attention_heads
        lowerCAmelCase_       :    Optional[Any]								=			hidden_dropout_prob
        lowerCAmelCase_       :    List[Any]								=			attention_probs_dropout_prob
        lowerCAmelCase_       :    Dict								=			max_position_embeddings
        lowerCAmelCase_       :    Union[str, Any]								=			type_vocab_size
        lowerCAmelCase_       :    List[Any]								=			type_sequence_label_size
        lowerCAmelCase_       :    str								=			initializer_range
        lowerCAmelCase_       :    Dict								=			num_labels
        lowerCAmelCase_       :    Union[str, Any]								=			num_choices
        lowerCAmelCase_       :    Union[str, Any]								=			summary_type
        lowerCAmelCase_       :    Optional[Any]								=			use_proj
        lowerCAmelCase_       :    List[Any]								=			scope



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        lowerCAmelCase_       :    List[Any]								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size	)
        lowerCAmelCase_       :    str								=			random_attention_mask([self.batch_size, self.seq_length]	)

        lowerCAmelCase_       :    Dict								=			None
        if self.use_input_lengths:
          lowerCAmelCase_       :    Any								=			(
              ids_tensor([self.batch_size]   ,      vocab_size=2	) + self.seq_length - 2
          )  # small variation of seq_length

        lowerCAmelCase_       :    Any								=			None
        if self.use_token_type_ids:
          lowerCAmelCase_       :    Union[str, Any]								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.n_langs	)

        lowerCAmelCase_       :    Dict								=			None
        lowerCAmelCase_       :    Optional[int]								=			None
        lowerCAmelCase_       :    List[str]								=			None
        if self.use_labels:
          lowerCAmelCase_       :    Tuple								=			ids_tensor([self.batch_size]   ,      self.type_sequence_label_size	)
          lowerCAmelCase_       :    Tuple								=			ids_tensor([self.batch_size, self.seq_length]   ,      self.num_labels	)
          lowerCAmelCase_       :    Any								=			ids_tensor([self.batch_size]   ,      2	).float()
          lowerCAmelCase_       :    List[Any]								=			ids_tensor([self.batch_size]   ,      self.num_choices	)

        lowerCAmelCase_       :    Union[str, Any]								=			self.get_config()

        return (
            config,
            input_ids,
            token_type_ids,
            input_lengths,
            sequence_labels,
            token_labels,
            is_impossible_labels,
            choice_labels,
            input_mask,
        )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[Any]	):
        return FlaubertConfig(
            vocab_size=self.vocab_size   ,      n_special=self.n_special   ,      emb_dim=self.hidden_size   ,      n_layers=self.num_hidden_layers   ,      n_heads=self.num_attention_heads   ,      dropout=self.hidden_dropout_prob   ,      attention_dropout=self.attention_probs_dropout_prob   ,      gelu_activation=self.gelu_activation   ,      sinusoidal_embeddings=self.sinusoidal_embeddings   ,      asm=self.asm   ,      causal=self.causal   ,      n_langs=self.n_langs   ,      max_position_embeddings=self.max_position_embeddings   ,      initializer_range=self.initializer_range   ,      summary_type=self.summary_type   ,      use_proj=self.use_proj   ,      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				str   ,      ):
        lowerCAmelCase_       :    Union[str, Any]								=			FlaubertModel(config=SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_   ,      lengths=SCREAMING_SNAKE_CASE_   ,      langs=SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_   ,      langs=SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[Any]								=			model(SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      ):
        lowerCAmelCase_       :    Any								=			FlaubertWithLMHeadModel(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Dict								=			model(SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.loss.shape   ,      ()	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.vocab_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      ):
        lowerCAmelCase_       :    Tuple								=			FlaubertForQuestionAnsweringSimple(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Union[str, Any]								=			model(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Optional[int]								=			model(SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.start_logits.shape   ,      (self.batch_size, self.seq_length)	)
        self.parent.assertEqual(result.end_logits.shape   ,      (self.batch_size, self.seq_length)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      ):
        lowerCAmelCase_       :    Optional[int]								=			FlaubertForQuestionAnswering(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_	)

        lowerCAmelCase_       :    Any								=			model(
            SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_   ,      cls_index=SCREAMING_SNAKE_CASE_   ,      is_impossible=SCREAMING_SNAKE_CASE_   ,      p_mask=SCREAMING_SNAKE_CASE_   ,      )

        lowerCAmelCase_       :    Optional[int]								=			model(
            SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_   ,      cls_index=SCREAMING_SNAKE_CASE_   ,      is_impossible=SCREAMING_SNAKE_CASE_   ,      )

        ((lowerCAmelCase_)						,)       :    int								=			result_with_labels.to_tuple()

        lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_   ,      start_positions=SCREAMING_SNAKE_CASE_   ,      end_positions=SCREAMING_SNAKE_CASE_	)

        ((lowerCAmelCase_)						,)       :    Dict								=			result_with_labels.to_tuple()

        self.parent.assertEqual(result_with_labels.loss.shape   ,      ()	)
        self.parent.assertEqual(result.start_top_log_probs.shape   ,      (self.batch_size, model.config.start_n_top)	)
        self.parent.assertEqual(result.start_top_index.shape   ,      (self.batch_size, model.config.start_n_top)	)
        self.parent.assertEqual(
            result.end_top_log_probs.shape   ,      (self.batch_size, model.config.start_n_top * model.config.end_n_top)	)
        self.parent.assertEqual(
            result.end_top_index.shape   ,      (self.batch_size, model.config.start_n_top * model.config.end_n_top)	)
        self.parent.assertEqual(result.cls_logits.shape   ,      (self.batch_size,)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      ):
        lowerCAmelCase_       :    Optional[int]								=			FlaubertForSequenceClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    Any								=			model(SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    List[Any]								=			model(SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)

        self.parent.assertEqual(result.loss.shape   ,      ()	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.type_sequence_label_size)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Any   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      ):
        lowerCAmelCase_       :    List[Any]								=			self.num_labels
        lowerCAmelCase_       :    Optional[Any]								=			FlaubertForTokenClassification(SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()

        lowerCAmelCase_       :    int								=			model(SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_	)
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.num_labels)	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Dict   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				List[Any]   ,      SCREAMING_SNAKE_CASE_    :				List[str]   ,      ):
        lowerCAmelCase_       :    Dict								=			self.num_choices
        lowerCAmelCase_       :    Optional[Any]								=			FlaubertForMultipleChoice(config=SCREAMING_SNAKE_CASE_	)
        model.to(SCREAMING_SNAKE_CASE_	)
        model.eval()
        lowerCAmelCase_       :    Tuple								=			input_ids.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
        lowerCAmelCase_       :    Union[str, Any]								=			token_type_ids.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
        lowerCAmelCase_       :    List[Any]								=			input_mask.unsqueeze(1	).expand(-1   ,      self.num_choices   ,      -1	).contiguous()
        lowerCAmelCase_       :    Optional[Any]								=			model(
            SCREAMING_SNAKE_CASE_   ,      attention_mask=SCREAMING_SNAKE_CASE_   ,      token_type_ids=SCREAMING_SNAKE_CASE_   ,      labels=SCREAMING_SNAKE_CASE_   ,      )
        self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_choices)	)





      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[Any]								=			self.prepare_config_and_inputs()
        (
            (
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,(
            lowerCAmelCase_
        )						,
        )       :    Dict								=			config_and_inputs
        lowerCAmelCase_       :    List[str]								=			{
            'input_ids': input_ids,
            'token_type_ids': token_type_ids,
            'lengths': input_lengths,
            'attention_mask': input_mask,
        }
        return config, inputs_dict







@require_torch
class 				UpperCamelCase__       (     lowercase_, lowercase_, unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE      =					(
          (
              FlaubertModel,
              FlaubertWithLMHeadModel,
              FlaubertForQuestionAnswering,
              FlaubertForQuestionAnsweringSimple,
              FlaubertForSequenceClassification,
              FlaubertForTokenClassification,
              FlaubertForMultipleChoice,
          )
          if is_torch_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE      =					(
          {
              """feature-extraction""": FlaubertModel,
              """fill-mask""": FlaubertWithLMHeadModel,
              """question-answering""": FlaubertForQuestionAnsweringSimple,
              """text-classification""": FlaubertForSequenceClassification,
              """token-classification""": FlaubertForTokenClassification,
              """zero-shot""": FlaubertForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )



      def 					SCREAMING_SNAKE_CASE__			(				self    :				int   ,      SCREAMING_SNAKE_CASE_    :				Tuple   ,      SCREAMING_SNAKE_CASE_    :				int   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				str   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]	):
        if (
            pipeline_test_casse_name == "QAPipelineTests"
            and tokenizer_name is not None
            and not tokenizer_name.endswith('Fast'	)
        ):
          # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
          # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
          # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
          return True

        return False



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]   ,      SCREAMING_SNAKE_CASE_    :				Union[str, Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]   ,      SCREAMING_SNAKE_CASE_    :				Optional[Any]=False	):
        lowerCAmelCase_       :    Any								=			super()._prepare_for_class(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_   ,      return_labels=SCREAMING_SNAKE_CASE_	)

        if return_labels:
          if model_class.__name__ == "FlaubertForQuestionAnswering":
            lowerCAmelCase_       :    Tuple								=			torch.zeros(
                self.model_tester.batch_size   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)
            lowerCAmelCase_       :    int								=			torch.zeros(
                self.model_tester.batch_size   ,      dtype=torch.long   ,      device=SCREAMING_SNAKE_CASE_	)

        return inputs_dict



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        lowerCAmelCase_       :    Tuple								=			FlaubertModelTester(self	)
        lowerCAmelCase_       :    str								=			ConfigTester(self   ,      config_class=SCREAMING_SNAKE_CASE_   ,      emb_dim=3_7	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Any	):
        self.config_tester.run_common_tests()



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_model(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    str								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_lm_head(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				List[str]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_simple_qa(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[str]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_qa(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Union[str, Any]	):
        lowerCAmelCase_       :    Optional[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_sequence_classif(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    Dict								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_token_classif(*SCREAMING_SNAKE_CASE_	)



      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[int]	):
        lowerCAmelCase_       :    List[Any]								=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_multiple_choice(*SCREAMING_SNAKE_CASE_	)



      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase_       :    Optional[Any]								=			FlaubertModel.from_pretrained(SCREAMING_SNAKE_CASE_	)
          self.assertIsNotNone(SCREAMING_SNAKE_CASE_	)





      @slow
      @require_torch_gpu
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Tuple	):
        lowerCAmelCase_						,lowerCAmelCase_       :    Any								=			self.model_tester.prepare_config_and_inputs_for_common()
        for model_class in self.all_model_classes:
          # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
          if model_class == FlaubertForMultipleChoice:
            return

          lowerCAmelCase_       :    int								=			True
          lowerCAmelCase_       :    Union[str, Any]								=			model_class(config=SCREAMING_SNAKE_CASE_	)

          lowerCAmelCase_       :    Any								=			self._prepare_for_class(SCREAMING_SNAKE_CASE_   ,      SCREAMING_SNAKE_CASE_	)
          lowerCAmelCase_       :    int								=			torch.jit.trace(
              SCREAMING_SNAKE_CASE_   ,      (inputs_dict['input_ids'].to('cpu'	), inputs_dict['attention_mask'].to('cpu'	))	)

          with tempfile.TemporaryDirectory() as tmp:
            torch.jit.save(SCREAMING_SNAKE_CASE_   ,      os.path.join(SCREAMING_SNAKE_CASE_   ,      'traced_model.pt'	)	)
            lowerCAmelCase_       :    Optional[Any]								=			torch.jit.load(os.path.join(SCREAMING_SNAKE_CASE_   ,      'traced_model.pt'	)   ,      map_location=SCREAMING_SNAKE_CASE_	)
            loaded(inputs_dict['input_ids'].to(SCREAMING_SNAKE_CASE_	)   ,      inputs_dict['attention_mask'].to(SCREAMING_SNAKE_CASE_	)	)







@require_torch
class 				UpperCamelCase__       (     unittest.TestCase  ):




      """simple docstring"""




      @slow
      def 					SCREAMING_SNAKE_CASE__			(				self    :				Optional[Any]	):
        lowerCAmelCase_       :    int								=			FlaubertModel.from_pretrained('flaubert/flaubert_base_cased'	)
        lowerCAmelCase_       :    List[Any]								=			torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]	)
        with torch.no_grad():
          lowerCAmelCase_       :    Optional[Any]								=			model(SCREAMING_SNAKE_CASE_	)[0]
        lowerCAmelCase_       :    Optional[Any]								=			torch.Size((1, 1_1, 7_6_8)	)
        self.assertEqual(output.shape   ,      SCREAMING_SNAKE_CASE_	)
        lowerCAmelCase_       :    Optional[int]								=			torch.tensor(
            [[[-2.62_51, -1.42_98, -0.02_27], [-2.85_10, -1.63_87, 0.22_58], [-2.81_14, -1.18_32, -0.30_66]]]	)

        self.assertTrue(torch.allclose(output[:, :3, :3]   ,      SCREAMING_SNAKE_CASE_   ,      atol=1E-4	)	)





