"""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    a__    (   _UpperCAmelCase	):


   def __init__(     self,				_UpperCAmelCase,				_UpperCAmelCase=13,				_UpperCAmelCase=7,				_UpperCAmelCase=True,				_UpperCAmelCase=True,				_UpperCAmelCase=True,				_UpperCAmelCase=True,				_UpperCAmelCase=True,				_UpperCAmelCase=False,				_UpperCAmelCase=False,				_UpperCAmelCase=False,				_UpperCAmelCase=2,				_UpperCAmelCase=99,				_UpperCAmelCase=0,				_UpperCAmelCase=32,				_UpperCAmelCase=5,				_UpperCAmelCase=4,				_UpperCAmelCase=0.1,				_UpperCAmelCase=0.1,				_UpperCAmelCase=512,				_UpperCAmelCase=12,				_UpperCAmelCase=2,				_UpperCAmelCase=0.02,				_UpperCAmelCase=3,				_UpperCAmelCase=4,				_UpperCAmelCase="last",				_UpperCAmelCase=None,				_UpperCAmelCase=None,				):
        '''simple docstring'''



        lowercase__				 =							parent
        lowercase__				 =							batch_size
        lowercase__				 =							seq_length
        lowercase__				 =							is_training
        lowercase__				 =							use_input_lengths
        lowercase__				 =							use_token_type_ids
        lowercase__				 =							use_labels
        lowercase__				 =							gelu_activation
        lowercase__				 =							sinusoidal_embeddings
        lowercase__				 =							causal
        lowercase__				 =							asm
        lowercase__				 =							n_langs
        lowercase__				 =							vocab_size
        lowercase__				 =							n_special
        lowercase__				 =							hidden_size
        lowercase__				 =							num_hidden_layers
        lowercase__				 =							num_attention_heads
        lowercase__				 =							hidden_dropout_prob
        lowercase__				 =							attention_probs_dropout_prob
        lowercase__				 =							max_position_embeddings
        lowercase__				 =							type_vocab_size
        lowercase__				 =							type_sequence_label_size
        lowercase__				 =							initializer_range
        lowercase__				 =							num_labels
        lowercase__				 =							num_choices
        lowercase__				 =							summary_type
        lowercase__				 =							use_proj
        lowercase__				 =							scope


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							ids_tensor([self.batch_size, self.seq_length],				self.vocab_size  )
        lowercase__				 =							random_attention_mask([self.batch_size, self.seq_length]  )

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

        lowercase__				 =							None
        if self.use_token_type_ids:
             lowercase__				 =							ids_tensor([self.batch_size, self.seq_length],				self.n_langs  )

        lowercase__				 =							None
        lowercase__				 =							None
        lowercase__				 =							None
        if self.use_labels:
             lowercase__				 =							ids_tensor([self.batch_size],				self.type_sequence_label_size  )
             lowercase__				 =							ids_tensor([self.batch_size, self.seq_length],				self.num_labels  )
             lowercase__				 =							ids_tensor([self.batch_size],				2  ).float()
             lowercase__				 =							ids_tensor([self.batch_size],				self.num_choices  )

        lowercase__				 =							self.get_config()

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


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        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 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							FlaubertModel(config=__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()
        lowercase__				 =							model(__UpperCamelCase,				lengths=__UpperCamelCase,				langs=__UpperCamelCase  )
        lowercase__				 =							model(__UpperCamelCase,				langs=__UpperCamelCase  )
        lowercase__				 =							model(__UpperCamelCase  )
        self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)  )


   def 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							FlaubertWithLMHeadModel(__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()

        lowercase__				 =							model(__UpperCamelCase,				token_type_ids=__UpperCamelCase,				labels=__UpperCamelCase  )
        self.parent.assertEqual(result.loss.shape,				()  )
        self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.vocab_size)  )


   def 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							FlaubertForQuestionAnsweringSimple(__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()

        lowercase__				 =							model(__UpperCamelCase  )

        lowercase__				 =							model(__UpperCamelCase,				start_positions=__UpperCamelCase,				end_positions=__UpperCamelCase  )
        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 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							FlaubertForQuestionAnswering(__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()

        lowercase__				 =							model(__UpperCamelCase  )

        lowercase__				 =							model(
            __UpperCamelCase,				start_positions=__UpperCamelCase,				end_positions=__UpperCamelCase,				cls_index=__UpperCamelCase,				is_impossible=__UpperCamelCase,				p_mask=__UpperCamelCase,				)

        lowercase__				 =							model(
            __UpperCamelCase,				start_positions=__UpperCamelCase,				end_positions=__UpperCamelCase,				cls_index=__UpperCamelCase,				is_impossible=__UpperCamelCase,				)

        ((lowercase__) ,						)				 =							result_with_labels.to_tuple()

        lowercase__				 =							model(__UpperCamelCase,				start_positions=__UpperCamelCase,				end_positions=__UpperCamelCase  )

        ((lowercase__) ,						)				 =							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 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							FlaubertForSequenceClassification(__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()

        lowercase__				 =							model(__UpperCamelCase  )
        lowercase__				 =							model(__UpperCamelCase,				labels=__UpperCamelCase  )

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


   def 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							self.num_labels
        lowercase__				 =							FlaubertForTokenClassification(__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()

        lowercase__				 =							model(__UpperCamelCase,				attention_mask=__UpperCamelCase,				labels=__UpperCamelCase  )
        self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.seq_length, self.num_labels)  )


   def 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				):
        '''simple docstring'''



        lowercase__				 =							self.num_choices
        lowercase__				 =							FlaubertForMultipleChoice(config=__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()
        lowercase__				 =							input_ids.unsqueeze(1  ).expand(-1,				self.num_choices,				-1  ).contiguous()
        lowercase__				 =							token_type_ids.unsqueeze(1  ).expand(-1,				self.num_choices,				-1  ).contiguous()
        lowercase__				 =							input_mask.unsqueeze(1  ).expand(-1,				self.num_choices,				-1  ).contiguous()
        lowercase__				 =							model(
            __UpperCamelCase,				attention_mask=__UpperCamelCase,				token_type_ids=__UpperCamelCase,				labels=__UpperCamelCase,				)
        self.parent.assertEqual(result.logits.shape,				(self.batch_size, self.num_choices)  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.prepare_config_and_inputs()
        (
            (
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						(
            lowercase__
        ) ,						
        )				 =							config_and_inputs
        lowercase__				 =							{
            "input_ids": input_ids,
            "token_type_ids": token_type_ids,
            "lengths": input_lengths,
            "attention_mask": input_mask,
        }
        return config, inputs_dict






@require_torch
class    a__    (   _UpperCAmelCase					,					_UpperCAmelCase					,					unittest.TestCase	):
   snake_case_							=      (
       (
           FlaubertModel,
           FlaubertWithLMHeadModel,
           FlaubertForQuestionAnswering,
           FlaubertForQuestionAnsweringSimple,
           FlaubertForSequenceClassification,
           FlaubertForTokenClassification,
           FlaubertForMultipleChoice,
       )
       if is_torch_available()
       else ()
   )
   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 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase  ):
        '''simple docstring'''



        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 	snake_case__	(     self,				_UpperCAmelCase,				_UpperCAmelCase,				_UpperCAmelCase=False  ):
        '''simple docstring'''



        lowercase__				 =							super()._prepare_for_class(__UpperCamelCase,				__UpperCamelCase,				return_labels=__UpperCamelCase  )

        if return_labels:
             if model_class.__name__ == "FlaubertForQuestionAnswering":
                  lowercase__				 =							torch.zeros(
                      self.model_tester.batch_size,				dtype=torch.long,				device=__UpperCamelCase  )
                  lowercase__				 =							torch.zeros(
                      self.model_tester.batch_size,				dtype=torch.long,				device=__UpperCamelCase  )

        return inputs_dict


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							FlaubertModelTester(self  )
        lowercase__				 =							ConfigTester(self,				config_class=__UpperCamelCase,				emb_dim=37  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        self.config_tester.run_common_tests()


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_model(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_lm_head(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_simple_qa(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_qa(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_sequence_classif(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_token_classif(*__UpperCamelCase  )


   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_flaubert_multiple_choice(*__UpperCamelCase  )


   @slow
   def 	snake_case__	(     self  ):
        '''simple docstring'''



        for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase__				 =							FlaubertModel.from_pretrained(__UpperCamelCase  )
             self.assertIsNotNone(__UpperCamelCase  )


   @slow
   @require_torch_gpu
   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__ ,						lowercase__				 =							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

             lowercase__				 =							True
             lowercase__				 =							model_class(config=__UpperCamelCase  )

             lowercase__				 =							self._prepare_for_class(__UpperCamelCase,				__UpperCamelCase  )
             lowercase__				 =							torch.jit.trace(
                 __UpperCamelCase,				(inputs_dict["input_ids"].to("cpu"  ), inputs_dict["attention_mask"].to("cpu"  ))  )

             with tempfile.TemporaryDirectory() as tmp:
                  torch.jit.save(__UpperCamelCase,				os.path.join(__UpperCamelCase,				"traced_model.pt"  )  )
                  lowercase__				 =							torch.jit.load(os.path.join(__UpperCamelCase,				"traced_model.pt"  ),				map_location=__UpperCamelCase  )
                  loaded(inputs_dict["input_ids"].to(__UpperCamelCase  ),				inputs_dict["attention_mask"].to(__UpperCamelCase  )  )






@require_torch
class    a__    (   unittest.TestCase	):


   @slow
   def 	snake_case__	(     self  ):
        '''simple docstring'''



        lowercase__				 =							FlaubertModel.from_pretrained("flaubert/flaubert_base_cased"  )
        lowercase__				 =							torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]  )
        with torch.no_grad():
             lowercase__				 =							model(__UpperCamelCase  )[0]
        lowercase__				 =							torch.Size((1, 11, 768)  )
        self.assertEqual(output.shape,				__UpperCamelCase  )
        lowercase__				 =							torch.tensor(
            [[[-2.6_251, -1.4_298, -0.0_227], [-2.8_510, -1.6_387, 0.2_258], [-2.8_114, -1.1_832, -0.3_066]]]  )

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





"""simple docstring"""


from __future__ import annotations







def 					__a   (		A    ,				A      ):






     '''simple docstring'''



     if partitions <= 0:
          raise ValueError("partitions must be a positive number!"      )
     if partitions > number_of_bytes:
          raise ValueError("partitions can not > number_of_bytes!"      )
     lowercase__				 =							number_of_bytes // partitions
     lowercase__				 =							[]
     for i in range(A      ):
          lowercase__				 =							i * bytes_per_partition + 1
          lowercase__				 =							(
              number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
          )
          allocation_list.append(f'''{start_bytes}-{end_bytes}'''      )
     return allocation_list


if __name__ == "__main__":
 import doctest

 doctest.testmod()




