
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 __snake_case		(				lowerCAmelCase					):
    def __init__(  self		,snake_case		,snake_case=13		,snake_case=7		,snake_case=True		,snake_case=True		,snake_case=True		,snake_case=True		,snake_case=True		,snake_case=False		,snake_case=False		,snake_case=False		,snake_case=2		,snake_case=99		,snake_case=0		,snake_case=32		,snake_case=5		,snake_case=4		,snake_case=0.1		,snake_case=0.1		,snake_case=512		,snake_case=12		,snake_case=2		,snake_case=0.02		,snake_case=3		,snake_case=4		,snake_case="last"		,snake_case=None		,snake_case=None		,):



           '''simple docstring'''







           lowercase							:					Optional[Any]	     =				parent
           lowercase							:					Optional[Any]	     =				batch_size
           lowercase							:					Optional[Any]	     =				seq_length
           lowercase							:					str	     =				is_training
           lowercase							:					List[str]	     =				use_input_lengths
           lowercase							:					int	     =				use_token_type_ids
           lowercase							:					Optional[int]	     =				use_labels
           lowercase							:					Optional[Any]	     =				gelu_activation
           lowercase							:					Optional[int]	     =				sinusoidal_embeddings
           lowercase							:					Any	     =				causal
           lowercase							:					Optional[Any]	     =				asm
           lowercase							:					Any	     =				n_langs
           lowercase							:					Any	     =				vocab_size
           lowercase							:					str	     =				n_special
           lowercase							:					int	     =				hidden_size
           lowercase							:					str	     =				num_hidden_layers
           lowercase							:					List[Any]	     =				num_attention_heads
           lowercase							:					Optional[Any]	     =				hidden_dropout_prob
           lowercase							:					Optional[int]	     =				attention_probs_dropout_prob
           lowercase							:					Optional[Any]	     =				max_position_embeddings
           lowercase							:					Optional[Any]	     =				type_vocab_size
           lowercase							:					Dict	     =				type_sequence_label_size
           lowercase							:					Dict	     =				initializer_range
           lowercase							:					Optional[Any]	     =				num_labels
           lowercase							:					str	     =				num_choices
           lowercase							:					Dict	     =				summary_type
           lowercase							:					List[Any]	     =				use_proj
           lowercase							:					int	     =				scope
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







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

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

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

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

           lowercase							:					List[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				):



           '''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 				_SCREAMING_SNAKE_CASE	(  self		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					List[Any]	     =				FlaubertModel(config=snake_case				)
           model.to(snake_case				)
           model.eval()
           lowercase							:					Dict	     =				model(snake_case		,lengths=snake_case		,langs=snake_case				)
           lowercase							:					Any	     =				model(snake_case		,langs=snake_case				)
           lowercase							:					Union[str, Any]	     =				model(snake_case				)
           self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size)				)
    def 				_SCREAMING_SNAKE_CASE	(  self		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					Optional[Any]	     =				FlaubertWithLMHeadModel(snake_case				)
           model.to(snake_case				)
           model.eval()

           lowercase							:					List[Any]	     =				model(snake_case		,token_type_ids=snake_case		,labels=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		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					Optional[int]	     =				FlaubertForQuestionAnsweringSimple(snake_case				)
           model.to(snake_case				)
           model.eval()

           lowercase							:					Optional[int]	     =				model(snake_case				)

           lowercase							:					Any	     =				model(snake_case		,start_positions=snake_case		,end_positions=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		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					List[Any]	     =				FlaubertForQuestionAnswering(snake_case				)
           model.to(snake_case				)
           model.eval()

           lowercase							:					str	     =				model(snake_case				)

           lowercase							:					Any	     =				model(
               snake_case		,start_positions=snake_case		,end_positions=snake_case		,cls_index=snake_case		,is_impossible=snake_case		,p_mask=snake_case		,)

           lowercase							:					Tuple	     =				model(
               snake_case		,start_positions=snake_case		,end_positions=snake_case		,cls_index=snake_case		,is_impossible=snake_case		,)

           ((lowercase)     ,      )							:					Union[str, Any]	     =				result_with_labels.to_tuple()

           lowercase							:					Tuple	     =				model(snake_case		,start_positions=snake_case		,end_positions=snake_case				)

           ((lowercase)     ,      )							:					Optional[int]	     =				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		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					Union[str, Any]	     =				FlaubertForSequenceClassification(snake_case				)
           model.to(snake_case				)
           model.eval()

           lowercase							:					List[Any]	     =				model(snake_case				)
           lowercase							:					Optional[int]	     =				model(snake_case		,labels=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		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







           lowercase							:					Any	     =				self.num_labels
           lowercase							:					str	     =				FlaubertForTokenClassification(snake_case				)
           model.to(snake_case				)
           model.eval()

           lowercase							:					Union[str, Any]	     =				model(snake_case		,attention_mask=snake_case		,labels=snake_case				)
           self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.seq_length, self.num_labels)				)
    def 				_SCREAMING_SNAKE_CASE	(  self		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case		,):



           '''simple docstring'''







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



           '''simple docstring'''







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






@require_torch
class __snake_case		(				lowerCAmelCase ,     lowerCAmelCase ,     unittest.TestCase					):
    _a		:						Optional[Any]=    (
        (
            FlaubertModel,
            FlaubertWithLMHeadModel,
            FlaubertForQuestionAnswering,
            FlaubertForQuestionAnsweringSimple,
            FlaubertForSequenceClassification,
            FlaubertForTokenClassification,
            FlaubertForMultipleChoice,
        )
        if is_torch_available()
        else ()
    )
    _a		:						str=    (
        {
            "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		,snake_case		,snake_case		,snake_case		,snake_case		,snake_case				):



           '''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 				_SCREAMING_SNAKE_CASE	(  self		,snake_case		,snake_case		,snake_case=False				):



           '''simple docstring'''







           lowercase							:					Dict	     =				super()._prepare_for_class(snake_case		,snake_case		,return_labels=snake_case				)

           if return_labels:
                  if model_class.__name__ == "FlaubertForQuestionAnswering":
                         lowercase							:					int	     =				torch.zeros(
                             self.model_tester.batch_size		,dtype=torch.long		,device=snake_case				)
                         lowercase							:					str	     =				torch.zeros(
                             self.model_tester.batch_size		,dtype=torch.long		,device=snake_case				)

           return inputs_dict
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					List[Any]	     =				FlaubertModelTester(self				)
           lowercase							:					Union[str, Any]	     =				ConfigTester(self		,config_class=snake_case		,emb_dim=37				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           self.config_tester.run_common_tests()
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Tuple	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_model(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					int	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_lm_head(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Any	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_simple_qa(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					str	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_qa(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Optional[Any]	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_sequence_classif(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					List[Any]	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_token_classif(*snake_case				)
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Optional[int]	     =				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_flaubert_multiple_choice(*snake_case				)
    @slow
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowercase							:					Tuple	     =				FlaubertModel.from_pretrained(snake_case				)
                  self.assertIsNotNone(snake_case				)
    @slow
    @require_torch_gpu
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase     ,      lowercase							:					Optional[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

                  lowercase							:					str	     =				True
                  lowercase							:					str	     =				model_class(config=snake_case				)

                  lowercase							:					Any	     =				self._prepare_for_class(snake_case		,snake_case				)
                  lowercase							:					Optional[int]	     =				torch.jit.trace(
                      snake_case		,(inputs_dict["""input_ids"""].to("""cpu"""				), inputs_dict["""attention_mask"""].to("""cpu"""				))				)

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






@require_torch
class __snake_case		(				unittest.TestCase					):
    @slow
    def 				_SCREAMING_SNAKE_CASE	(  self				):



           '''simple docstring'''







           lowercase							:					Any	     =				FlaubertModel.from_pretrained("""flaubert/flaubert_base_cased"""				)
           lowercase							:					Optional[int]	     =				torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]				)
           with torch.no_grad():
                  lowercase							:					Optional[int]	     =				model(snake_case				)[0]
           lowercase							:					Tuple	     =				torch.Size((1, 11, 768)				)
           self.assertEqual(output.shape		,snake_case				)
           lowercase							:					List[str]	     =				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]		,snake_case		,atol=1e-4				)				)


from __future__ import annotations

import numpy as np







def 						_snake_case(  SCREAMING_SNAKE_CASE__    )			->   tuple[np.ndarray, np.ndarray]:
       lowercase     ,      lowercase							:					Dict	     =				np.shape(SCREAMING_SNAKE_CASE__    )
       if rows != columns:
              lowercase							:					str	     =				(
                  """'table' has to be of square shaped array but got a """
                  f"{rows}x{columns} array:\n{table}"
              )
              raise ValueError(SCREAMING_SNAKE_CASE__    )

       lowercase							:					Any	     =				np.zeros((rows, columns)    )
       lowercase							:					int	     =				np.zeros((rows, columns)    )
       for i in range(SCREAMING_SNAKE_CASE__    ):
              for j in range(SCREAMING_SNAKE_CASE__    ):
                     lowercase							:					Optional[int]	     =				sum(lower[i][k] * upper[k][j] for k in range(SCREAMING_SNAKE_CASE__    )    )
                     if upper[j][j] == 0:
                            raise ArithmeticError("""No LU decomposition exists"""    )
                     lowercase							:					str	     =				(table[i][j] - total) / upper[j][j]
              lowercase							:					Optional[Any]	     =				1
              for j in range(SCREAMING_SNAKE_CASE__ ,     SCREAMING_SNAKE_CASE__    ):
                     lowercase							:					Any	     =				sum(lower[i][k] * upper[k][j] for k in range(SCREAMING_SNAKE_CASE__    )    )
                     lowercase							:					Tuple	     =				table[i][j] - total
       return lower, upper


if __name__ == "__main__":
  import doctest

  doctest.testmod()
