'''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       (__magic_name__   ):






       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_=5_12				,     UpperCamelCase_=12				,     UpperCamelCase_=2				,     UpperCamelCase_=0.0_2				,     UpperCamelCase_=3				,     UpperCamelCase_=4				,     UpperCamelCase_="last"				,     UpperCamelCase_=None				,     UpperCamelCase_=None				,     ):
              __UpperCAmelCase  :				Optional[Any]       				=		parent
              __UpperCAmelCase  :				Union[str, Any]       				=		batch_size
              __UpperCAmelCase  :				Optional[Any]       				=		seq_length
              __UpperCAmelCase  :				Optional[int]       				=		is_training
              __UpperCAmelCase  :				Any       				=		use_input_lengths
              __UpperCAmelCase  :				Optional[Any]       				=		use_token_type_ids
              __UpperCAmelCase  :				List[str]       				=		use_labels
              __UpperCAmelCase  :				Union[str, Any]       				=		gelu_activation
              __UpperCAmelCase  :				Tuple       				=		sinusoidal_embeddings
              __UpperCAmelCase  :				str       				=		causal
              __UpperCAmelCase  :				Union[str, Any]       				=		asm
              __UpperCAmelCase  :				Optional[int]       				=		n_langs
              __UpperCAmelCase  :				Union[str, Any]       				=		vocab_size
              __UpperCAmelCase  :				Optional[int]       				=		n_special
              __UpperCAmelCase  :				List[str]       				=		hidden_size
              __UpperCAmelCase  :				str       				=		num_hidden_layers
              __UpperCAmelCase  :				Dict       				=		num_attention_heads
              __UpperCAmelCase  :				Dict       				=		hidden_dropout_prob
              __UpperCAmelCase  :				Any       				=		attention_probs_dropout_prob
              __UpperCAmelCase  :				Dict       				=		max_position_embeddings
              __UpperCAmelCase  :				str       				=		type_vocab_size
              __UpperCAmelCase  :				Dict       				=		type_sequence_label_size
              __UpperCAmelCase  :				Tuple       				=		initializer_range
              __UpperCAmelCase  :				Optional[Any]       				=		num_labels
              __UpperCAmelCase  :				Union[str, Any]       				=		num_choices
              __UpperCAmelCase  :				Union[str, Any]       				=		summary_type
              __UpperCAmelCase  :				Dict       				=		use_proj
              __UpperCAmelCase  :				Dict       				=		scope






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				str       				=		ids_tensor([self.batch_size, self.seq_length]				,     self.vocab_size      )
              __UpperCAmelCase  :				str       				=		random_attention_mask([self.batch_size, self.seq_length]      )

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

              __UpperCAmelCase  :				Optional[Any]       				=		None
              if self.use_token_type_ids:
                     __UpperCAmelCase  :				int       				=		ids_tensor([self.batch_size, self.seq_length]				,     self.n_langs      )

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

              __UpperCAmelCase  :				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 			_snake_case						(      self      ):
              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_				,     ):
              __UpperCAmelCase  :				Tuple       				=		FlaubertModel(config=UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()
              __UpperCAmelCase  :				int       				=		model(UpperCamelCase_				,     lengths=UpperCamelCase_				,     langs=UpperCamelCase_      )
              __UpperCAmelCase  :				int       				=		model(UpperCamelCase_				,     langs=UpperCamelCase_      )
              __UpperCAmelCase  :				Optional[Any]       				=		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_				,     ):
              __UpperCAmelCase  :				List[str]       				=		FlaubertWithLMHeadModel(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              __UpperCAmelCase  :				Tuple       				=		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_				,     ):
              __UpperCAmelCase  :				Union[str, Any]       				=		FlaubertForQuestionAnsweringSimple(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              __UpperCAmelCase  :				int       				=		model(UpperCamelCase_      )

              __UpperCAmelCase  :				Dict       				=		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_				,     ):
              __UpperCAmelCase  :				Tuple       				=		FlaubertForQuestionAnswering(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              __UpperCAmelCase  :				Dict       				=		model(UpperCamelCase_      )

              __UpperCAmelCase  :				str       				=		model(
                  UpperCamelCase_				,     start_positions=UpperCamelCase_				,     end_positions=UpperCamelCase_				,     cls_index=UpperCamelCase_				,     is_impossible=UpperCamelCase_				,     p_mask=UpperCamelCase_				,     )

              __UpperCAmelCase  :				Dict       				=		model(
                  UpperCamelCase_				,     start_positions=UpperCamelCase_				,     end_positions=UpperCamelCase_				,     cls_index=UpperCamelCase_				,     is_impossible=UpperCamelCase_				,     )

              (__UpperCAmelCase )  :				str       				=		result_with_labels.to_tuple()

              __UpperCAmelCase  :				List[Any]       				=		model(UpperCamelCase_				,     start_positions=UpperCamelCase_				,     end_positions=UpperCamelCase_      )

              (__UpperCAmelCase )  :				Tuple       				=		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_				,     ):
              __UpperCAmelCase  :				Optional[Any]       				=		FlaubertForSequenceClassification(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              __UpperCAmelCase  :				Any       				=		model(UpperCamelCase_      )
              __UpperCAmelCase  :				int       				=		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_				,     ):
              __UpperCAmelCase  :				int       				=		self.num_labels
              __UpperCAmelCase  :				Optional[Any]       				=		FlaubertForTokenClassification(UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()

              __UpperCAmelCase  :				str       				=		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_				,     ):
              __UpperCAmelCase  :				Optional[Any]       				=		self.num_choices
              __UpperCAmelCase  :				Dict       				=		FlaubertForMultipleChoice(config=UpperCamelCase_      )
              model.to(UpperCamelCase_      )
              model.eval()
              __UpperCAmelCase  :				str       				=		input_ids.unsqueeze(1      ).expand(-1				,     self.num_choices				,     -1      ).contiguous()
              __UpperCAmelCase  :				Any       				=		token_type_ids.unsqueeze(1      ).expand(-1				,     self.num_choices				,     -1      ).contiguous()
              __UpperCAmelCase  :				List[Any]       				=		input_mask.unsqueeze(1      ).expand(-1				,     self.num_choices				,     -1      ).contiguous()
              __UpperCAmelCase  :				str       				=		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      ):
              __UpperCAmelCase  :				Optional[int]       				=		self.prepare_config_and_inputs()
              (
                  __UpperCAmelCase 
              )  :				Dict       				=		config_and_inputs
              __UpperCAmelCase  :				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 		__A       (__magic_name__ ,					__magic_name__ ,					unittest.TestCase   ):
       snake_case       :Tuple				    =					(
           (
               FlaubertModel,
               FlaubertWithLMHeadModel,
               FlaubertForQuestionAnswering,
               FlaubertForQuestionAnsweringSimple,
               FlaubertForSequenceClassification,
               FlaubertForTokenClassification,
               FlaubertForMultipleChoice,
           )
           if is_torch_available()
           else ()
       )
       snake_case       :Optional[Any]				    =					(
           {
               "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_      ):
              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      ):
              __UpperCAmelCase  :				Tuple       				=		super()._prepare_for_class(UpperCamelCase_				,     UpperCamelCase_				,     return_labels=UpperCamelCase_      )

              if return_labels:
                     if model_class.__name__ == "FlaubertForQuestionAnswering":
                            __UpperCAmelCase  :				List[Any]       				=		torch.zeros(
                                self.model_tester.batch_size				,     dtype=torch.long				,     device=UpperCamelCase_      )
                            __UpperCAmelCase  :				Tuple       				=		torch.zeros(
                                self.model_tester.batch_size				,     dtype=torch.long				,     device=UpperCamelCase_      )

              return inputs_dict






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Optional[int]       				=		FlaubertModelTester(self      )
              __UpperCAmelCase  :				int       				=		ConfigTester(self				,     config_class=UpperCamelCase_				,     emb_dim=37      )






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






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Any       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_model(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Optional[int]       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_lm_head(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				str       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_simple_qa(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				List[Any]       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_qa(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Any       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Any       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_token_classif(*UpperCamelCase_      )






       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Optional[Any]       				=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_flaubert_multiple_choice(*UpperCamelCase_      )






       @slow
       def 			_snake_case						(      self      ):
              for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     __UpperCAmelCase  :				List[str]       				=		FlaubertModel.from_pretrained(UpperCamelCase_      )
                     self.assertIsNotNone(UpperCamelCase_      )







       @slow
       @require_torch_gpu
       def 			_snake_case						(      self      ):
              __UpperCAmelCase  :				Optional[int]       				=		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

                     __UpperCAmelCase  :				Optional[int]       				=		True
                     __UpperCAmelCase  :				Tuple       				=		model_class(config=UpperCamelCase_      )

                     __UpperCAmelCase  :				Dict       				=		self._prepare_for_class(UpperCamelCase_				,     UpperCamelCase_      )
                     __UpperCAmelCase  :				Any       				=		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"      )      )
                            __UpperCAmelCase  :				Dict       				=		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      ):
              __UpperCAmelCase  :				Union[str, Any]       				=		FlaubertModel.from_pretrained("flaubert/flaubert_base_cased"      )
              __UpperCAmelCase  :				int       				=		torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]]      )
              with torch.no_grad():
                     __UpperCAmelCase  :				Any       				=		model(UpperCamelCase_      )[0]
              __UpperCAmelCase  :				List[Any]       				=		torch.Size((1, 11, 7_68)      )
              self.assertEqual(output.shape				,     UpperCamelCase_      )
              __UpperCAmelCase  :				int       				=		torch.tensor(
                  [[[-2.6_2_5_1, -1.4_2_9_8, -0.0_2_2_7], [-2.8_5_1_0, -1.6_3_8_7, 0.2_2_5_8], [-2.8_1_1_4, -1.1_8_3_2, -0.3_0_6_6]]]      )

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







'''simple docstring'''




from collections import Counter

import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split

_a   :	str 							=   datasets.load_iris()

_a   :	List[Any] 							=   np.array(data["data"])
_a   :	Optional[Any] 							=   np.array(data["target"])
_a   :	Dict 							=   data["target_names"]

_a							,					_a							,					_a							,					_a   :	Any 							=   train_test_split(X, y)

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__						)					->       Tuple:





       """simple docstring"""


       return np.linalg.norm(np.array(lowerCamelCase__						) - np.array(lowerCamelCase__						)						)

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__=5						)					->       int:





       """simple docstring"""


       __UpperCAmelCase  :				List[Any]       				=		zip(lowerCamelCase__							,    lowerCamelCase__						)
       # List of distances of all points from the point to be classified
       __UpperCAmelCase  :				int       				=		[]
       for data_point in data:
              __UpperCAmelCase  :				Optional[Any]       				=		euclidean_distance(data_point[0]							,    lowerCamelCase__						)
              distances.append((distance, data_point[1])						)
       # Choosing 'k' points with the least distances.
       __UpperCAmelCase  :				Union[str, Any]       				=		[i[1] for i in sorted(lowerCamelCase__						)[:k]]
       # Most commonly occurring class among them
       # is the class into which the point is classified
       __UpperCAmelCase  :				Dict       				=		Counter(lowerCamelCase__						).most_common(1						)[0][0]
       return classes[result]


if __name__ == "__main__":
   print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))






