


"""simple docstring"""







import unittest

from transformers import BigBirdConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
		import jax

		from transformers.models.big_bird.modeling_flax_big_bird import (
		    FlaxBigBirdForCausalLM,
		    FlaxBigBirdForMaskedLM,
		    FlaxBigBirdForMultipleChoice,
		    FlaxBigBirdForPreTraining,
		    FlaxBigBirdForQuestionAnswering,
		    FlaxBigBirdForSequenceClassification,
		    FlaxBigBirdForTokenClassification,
		    FlaxBigBirdModel,
		)




class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	def __init__(				self    :       str    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       Optional[int]=2    ,    UpperCAmelCase__    :       List[Any]=5_6    ,    UpperCAmelCase__    :       int=True    ,    UpperCAmelCase__    :       Optional[Any]=True    ,    UpperCAmelCase__    :       Tuple=True    ,    UpperCAmelCase__    :       Any=True    ,    UpperCAmelCase__    :       Tuple=9_9    ,    UpperCAmelCase__    :       int=3_2    ,    UpperCAmelCase__    :       Any=2    ,    UpperCAmelCase__    :       Tuple=2    ,    UpperCAmelCase__    :       Union[str, Any]=7    ,    UpperCAmelCase__    :       Optional[Any]="gelu_new"    ,    UpperCAmelCase__    :       Optional[int]=0.1    ,    UpperCAmelCase__    :       List[Any]=0.1    ,    UpperCAmelCase__    :       Optional[Any]=5_1_2    ,    UpperCAmelCase__    :       Optional[int]=1_6    ,    UpperCAmelCase__    :       str=2    ,    UpperCAmelCase__    :       Optional[Any]=0.02    ,    UpperCAmelCase__    :       Union[str, Any]=4    ,    UpperCAmelCase__    :       str="block_sparse"    ,    UpperCAmelCase__    :       str=True    ,    UpperCAmelCase__    :       Optional[Any]=False    ,    UpperCAmelCase__    :       Optional[int]=2    ,    UpperCAmelCase__    :       str=3    ,    ) ->			List[Any]:
						__SCREAMING_SNAKE_CASE		     =       parent
						__SCREAMING_SNAKE_CASE		     =       batch_size
						__SCREAMING_SNAKE_CASE		     =       seq_length
						__SCREAMING_SNAKE_CASE		     =       is_training
						__SCREAMING_SNAKE_CASE		     =       use_attention_mask
						__SCREAMING_SNAKE_CASE		     =       use_token_type_ids
						__SCREAMING_SNAKE_CASE		     =       use_labels
						__SCREAMING_SNAKE_CASE		     =       vocab_size
						__SCREAMING_SNAKE_CASE		     =       hidden_size
						__SCREAMING_SNAKE_CASE		     =       num_hidden_layers
						__SCREAMING_SNAKE_CASE		     =       num_attention_heads
						__SCREAMING_SNAKE_CASE		     =       intermediate_size
						__SCREAMING_SNAKE_CASE		     =       hidden_act
						__SCREAMING_SNAKE_CASE		     =       hidden_dropout_prob
						__SCREAMING_SNAKE_CASE		     =       attention_probs_dropout_prob
						__SCREAMING_SNAKE_CASE		     =       max_position_embeddings
						__SCREAMING_SNAKE_CASE		     =       type_vocab_size
						__SCREAMING_SNAKE_CASE		     =       type_sequence_label_size
						__SCREAMING_SNAKE_CASE		     =       initializer_range
						__SCREAMING_SNAKE_CASE		     =       num_choices

						__SCREAMING_SNAKE_CASE		     =       rescale_embeddings
						__SCREAMING_SNAKE_CASE		     =       attention_type
						__SCREAMING_SNAKE_CASE		     =       use_bias
						__SCREAMING_SNAKE_CASE		     =       block_size
						__SCREAMING_SNAKE_CASE		     =       num_random_blocks




	def 						UpperCAmelCase_   (				self    :       Any     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size     )

						__SCREAMING_SNAKE_CASE		     =       None
						if self.use_attention_mask:
											__SCREAMING_SNAKE_CASE		     =       random_attention_mask([self.batch_size, self.seq_length]     )

						__SCREAMING_SNAKE_CASE		     =       None
						if self.use_token_type_ids:
											__SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.type_vocab_size     )

						__SCREAMING_SNAKE_CASE		     =       BigBirdConfig(
						    vocab_size=self.vocab_size    ,    hidden_size=self.hidden_size    ,    num_hidden_layers=self.num_hidden_layers    ,    num_attention_heads=self.num_attention_heads    ,    intermediate_size=self.intermediate_size    ,    hidden_act=self.hidden_act    ,    hidden_dropout_prob=self.hidden_dropout_prob    ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,    max_position_embeddings=self.max_position_embeddings    ,    type_vocab_size=self.type_vocab_size    ,    is_decoder=UpperCAmelCase__    ,    initializer_range=self.initializer_range    ,    attention_type=self.attention_type    ,    block_size=self.block_size    ,    num_random_blocks=self.num_random_blocks    ,    use_bias=self.use_bias    ,    rescale_embeddings=self.rescale_embeddings    ,    )

						return config, input_ids, token_type_ids, attention_mask




	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			List[Any]:
						__SCREAMING_SNAKE_CASE		     =       self.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       config_and_inputs
						__SCREAMING_SNAKE_CASE		     =       {
						    "input_ids": input_ids,
						    "token_type_ids": token_type_ids,
						    "attention_mask": attention_mask,
						}
						return config, inputs_dict




@require_flax
class 				UpperCamelCase_			(				UpperCamelCase    ,						unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						Optional[int]					      =    (
	    (
	        FlaxBigBirdForCausalLM,
	        FlaxBigBirdModel,
	        FlaxBigBirdForPreTraining,
	        FlaxBigBirdForMaskedLM,
	        FlaxBigBirdForMultipleChoice,
	        FlaxBigBirdForQuestionAnswering,
	        FlaxBigBirdForSequenceClassification,
	        FlaxBigBirdForTokenClassification,
	    )
	    if is_flax_available()
	    else ()
	)

	snake_case__       :						Optional[int]					      =    False
	snake_case__       :						List[str]					      =    False




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       FlaxBigBirdModelTester(self     )




	@slow
	# copied from `test_modeling_flax_common` because it takes much longer than other models
	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Tuple:
						super().test_from_pretrained_save_pretrained()




	@slow
	# copied from `test_modeling_flax_common` because it takes much longer than other models
	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Optional[int]:
						super().test_from_pretrained_with_no_automatic_init()




	@slow
	# copied from `test_modeling_flax_common` because it takes much longer than other models
	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Union[str, Any]:
						super().test_no_automatic_init()




	@slow
	# copied from `test_modeling_flax_common` because it takes much longer than other models
	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			str:
						super().test_hidden_states_output()




	@slow
	def 						UpperCAmelCase_   (				self    :       int     ) ->			Union[str, Any]:
						for model_class_name in self.all_model_classes:
											__SCREAMING_SNAKE_CASE		     =       model_class_name.from_pretrained("google/bigbird-roberta-base"     )
											self.assertIsNotNone(UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			str:
						if self.test_attn_probs:
											super().test_attention_outputs()




	@slow
	# copied from `test_modeling_flax_common` because it takes much longer than other models
	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			Any:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__     ):
																__SCREAMING_SNAKE_CASE		     =       self._prepare_for_class(UpperCAmelCase__    ,    UpperCAmelCase__     )
																__SCREAMING_SNAKE_CASE		     =       model_class(UpperCAmelCase__     )

																@jax.jit
																def model_jitted(UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       int=None    ,    **UpperCAmelCase__    :       str     ):
																					return model(input_ids=UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    **UpperCAmelCase__     )

																with self.subTest("JIT Enabled"     ):
																					__SCREAMING_SNAKE_CASE		     =       model_jitted(**UpperCAmelCase__     ).to_tuple()

																with self.subTest("JIT Disabled"     ):
																					with jax.disable_jit():
																										__SCREAMING_SNAKE_CASE		     =       model_jitted(**UpperCAmelCase__     ).to_tuple()

																self.assertEqual(len(UpperCAmelCase__     )    ,    len(UpperCAmelCase__     )     )
																for jitted_output, output in zip(UpperCAmelCase__    ,    UpperCAmelCase__     ):
																					self.assertEqual(jitted_output.shape    ,    output.shape     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       List[Any]=1E-5    ,    UpperCAmelCase__    :       Optional[Any]="outputs"    ,    UpperCAmelCase__    :       str=None     ) ->			List[str]:
						# `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version,
						# an effort was done to return `attention_probs` (yet to be verified).
						if name.startswith("outputs.attentions"     ):
											return
						else:
											super().check_pt_flax_outputs(UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__     )




"""simple docstring"""







import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
a__       :							Dict        =  {'''LayoutLMv2Config''', '''LayoutLMv3Config'''}




@is_pipeline_test
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						str					      =    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
	snake_case__       :						Tuple					      =    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

	if model_mapping is not None:
		snake_case__       :						List[Any]					      =    {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
	if tf_model_mapping is not None:
		snake_case__       :						Dict					      =    {
		    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
		}




	@require_torch
	def 						UpperCAmelCase_   (				self    :       str     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       pipeline(
						    task="text-classification"    ,    model="hf-internal-testing/tiny-random-distilbert"    ,    framework="pt"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier(["This is great !", "This is bad"]    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [
						        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
						        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
						    ]    ,    )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"    ,    top_k=1     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )

						# Legacy behavior
						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"    ,    return_all_scores=UpperCAmelCase__     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"    ,    return_all_scores=UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]]     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier(["This is great !", "Something else"]    ,    return_all_scores=UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [
						        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
						        [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
						    ]    ,    )

						__SCREAMING_SNAKE_CASE		     =       text_classifier(["This is great !", "Something else"]    ,    return_all_scores=UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [
						        {"label": "LABEL_0", "score": 0.504},
						        {"label": "LABEL_0", "score": 0.504},
						    ]    ,    )




	@require_torch
	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Optional[int]:
						import torch

						__SCREAMING_SNAKE_CASE		     =       pipeline(
						    task="text-classification"    ,    model="hf-internal-testing/tiny-random-distilbert"    ,    framework="pt"    ,    device=torch.device("cpu"     )    ,    )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )




	@require_tf
	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Optional[int]:
						__SCREAMING_SNAKE_CASE		     =       pipeline(
						    task="text-classification"    ,    model="hf-internal-testing/tiny-random-distilbert"    ,    framework="tf"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "LABEL_0", "score": 0.504}]     )




	@slow
	@require_torch
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       pipeline("text-classification"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "POSITIVE", "score": 1.0}]     )
						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is bad !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "NEGATIVE", "score": 1.0}]     )
						__SCREAMING_SNAKE_CASE		     =       text_classifier("Birds are a type of animal"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "POSITIVE", "score": 0.988}]     )




	@slow
	@require_tf
	def 						UpperCAmelCase_   (				self    :       List[str]     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       pipeline("text-classification"    ,    framework="tf"     )

						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is great !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "POSITIVE", "score": 1.0}]     )
						__SCREAMING_SNAKE_CASE		     =       text_classifier("This is bad !"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "NEGATIVE", "score": 1.0}]     )
						__SCREAMING_SNAKE_CASE		     =       text_classifier("Birds are a type of animal"     )
						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": "POSITIVE", "score": 0.988}]     )




	def 						UpperCAmelCase_   (				self    :       Any    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       Tuple     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       TextClassificationPipeline(model=UpperCAmelCase__    ,    tokenizer=UpperCAmelCase__     )
						return text_classifier, ["HuggingFace is in", "This is another test"]




	def 						UpperCAmelCase_   (				self    :       str    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Optional[int]     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       text_classifier.model
						# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
						__SCREAMING_SNAKE_CASE		     =       "HuggingFace is in"
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__     )

						self.assertEqual(nested_simplify(UpperCAmelCase__     )    ,    [{"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}]     )
						self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()     )

						__SCREAMING_SNAKE_CASE		     =       ["HuggingFace is in ", "Paris is in France"]
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [{"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}, {"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}]    ,    )
						self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()     )
						self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()     )

						# Forcing to get all results with `top_k=None`
						# This is NOT the legacy format
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__    ,    top_k=UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       len(model.config.idalabel.values()     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [[{"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}] * N, [{"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}] * N]    ,    )

						__SCREAMING_SNAKE_CASE		     =       {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
						__SCREAMING_SNAKE_CASE		     =       text_classifier(UpperCAmelCase__     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    {"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}    ,    )
						self.assertTrue(outputs["label"] in model.config.idalabel.values()     )

						# This might be used a text pair, but tokenizer + pipe interaction
						# makes it hard to understand that it's not using the pair properly
						# https://github.com/huggingface/transformers/issues/17305
						# We disabled this usage instead as it was outputting wrong outputs.
						__SCREAMING_SNAKE_CASE		     =       [["HuggingFace is in ", "Paris is in France"]]
						with self.assertRaises(UpperCAmelCase__     ):
											text_classifier(UpperCAmelCase__     )

						# This used to be valid for doing text pairs
						# We're keeping it working because of backward compatibility
						__SCREAMING_SNAKE_CASE		     =       text_classifier([[["HuggingFace is in ", "Paris is in France"]]]     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__     )    ,    [{"label": ANY(UpperCAmelCase__     ), "score": ANY(UpperCAmelCase__     )}]    ,    )
						self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()     )
