


"""simple docstring"""







import unittest

from transformers import BertGenerationConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import BertGenerationDecoder, BertGenerationEncoder




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       Optional[Any]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Optional[Any]=1_3    ,    UpperCAmelCase__    :       Optional[Any]=7    ,    UpperCAmelCase__    :       Dict=True    ,    UpperCAmelCase__    :       str=True    ,    UpperCAmelCase__    :       str=9_9    ,    UpperCAmelCase__    :       List[Any]=3_2    ,    UpperCAmelCase__    :       Any=5    ,    UpperCAmelCase__    :       List[str]=4    ,    UpperCAmelCase__    :       Dict=3_7    ,    UpperCAmelCase__    :       str="gelu"    ,    UpperCAmelCase__    :       str=0.1    ,    UpperCAmelCase__    :       Optional[int]=0.1    ,    UpperCAmelCase__    :       Union[str, Any]=5_0    ,    UpperCAmelCase__    :       Dict=0.02    ,    UpperCAmelCase__    :       Union[str, Any]=True    ,    UpperCAmelCase__    :       Optional[int]=None    ,    ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       parent
						__SCREAMING_SNAKE_CASE		     =       batch_size
						__SCREAMING_SNAKE_CASE		     =       seq_length
						__SCREAMING_SNAKE_CASE		     =       is_training
						__SCREAMING_SNAKE_CASE		     =       use_input_mask
						__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		     =       initializer_range
						__SCREAMING_SNAKE_CASE		     =       use_labels
						__SCREAMING_SNAKE_CASE		     =       scope




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

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

						if self.use_labels:
											__SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    self.vocab_size     )

						__SCREAMING_SNAKE_CASE		     =       self.get_config()

						return config, input_ids, input_mask, token_labels




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			List[Any]:
						return BertGenerationConfig(
						    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    ,    is_decoder=UpperCAmelCase__    ,    initializer_range=self.initializer_range    ,    )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Dict:
						(
						    (
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,												
						)		     =       self.prepare_config_and_inputs()

						__SCREAMING_SNAKE_CASE		     =       True
						__SCREAMING_SNAKE_CASE		     =       floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
						__SCREAMING_SNAKE_CASE		     =       ids_tensor([self.batch_size, self.seq_length]    ,    vocab_size=2     )

						return (
						    config,
						    input_ids,
						    input_mask,
						    token_labels,
						    encoder_hidden_states,
						    encoder_attention_mask,
						)




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       Dict    ,    UpperCAmelCase__    :       List[str]    ,    **UpperCAmelCase__    :       Any    ,    ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationEncoder(config=UpperCAmelCase__     )
						model.to(UpperCAmelCase__     )
						model.eval()
						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )
						self.parent.assertEqual(result.last_hidden_state.shape    ,    (self.batch_size, self.seq_length, self.hidden_size)     )




	def 						UpperCAmelCase_   (				self    :       Tuple    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       Optional[int]    ,    UpperCAmelCase__    :       Union[str, Any]    ,    **UpperCAmelCase__    :       Optional[Any]    ,    ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       True
						__SCREAMING_SNAKE_CASE		     =       BertGenerationEncoder(config=UpperCAmelCase__     )
						model.to(UpperCAmelCase__     )
						model.eval()
						__SCREAMING_SNAKE_CASE		     =       model(
						    UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    encoder_hidden_states=UpperCAmelCase__    ,    encoder_attention_mask=UpperCAmelCase__    ,    )
						__SCREAMING_SNAKE_CASE		     =       model(
						    UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    encoder_hidden_states=UpperCAmelCase__    ,    )
						self.parent.assertEqual(result.last_hidden_state.shape    ,    (self.batch_size, self.seq_length, self.hidden_size)     )




	def 						UpperCAmelCase_   (				self    :       Optional[Any]    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       int    ,    UpperCAmelCase__    :       Union[str, Any]    ,    UpperCAmelCase__    :       List[Any]    ,    **UpperCAmelCase__    :       int    ,    ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       True
						__SCREAMING_SNAKE_CASE		     =       True
						__SCREAMING_SNAKE_CASE		     =       BertGenerationDecoder(config=UpperCAmelCase__     ).to(UpperCAmelCase__     ).eval()

						# first forward pass
						__SCREAMING_SNAKE_CASE		     =       model(
						    UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    encoder_hidden_states=UpperCAmelCase__    ,    encoder_attention_mask=UpperCAmelCase__    ,    use_cache=UpperCAmelCase__    ,    )
						__SCREAMING_SNAKE_CASE		     =       outputs.past_key_values

						# create hypothetical multiple next token and extent to next_input_ids
						__SCREAMING_SNAKE_CASE		     =       ids_tensor((self.batch_size, 3)    ,    config.vocab_size     )
						__SCREAMING_SNAKE_CASE		     =       ids_tensor((self.batch_size, 3)    ,    vocab_size=2     )

						# append to next input_ids and
						__SCREAMING_SNAKE_CASE		     =       torch.cat([input_ids, next_tokens]    ,    dim=-1     )
						__SCREAMING_SNAKE_CASE		     =       torch.cat([input_mask, next_mask]    ,    dim=-1     )

						__SCREAMING_SNAKE_CASE		     =       model(
						    UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    encoder_hidden_states=UpperCAmelCase__    ,    encoder_attention_mask=UpperCAmelCase__    ,    output_hidden_states=UpperCAmelCase__    ,    )["hidden_states"][0]
						__SCREAMING_SNAKE_CASE		     =       model(
						    UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    encoder_hidden_states=UpperCAmelCase__    ,    encoder_attention_mask=UpperCAmelCase__    ,    past_key_values=UpperCAmelCase__    ,    output_hidden_states=UpperCAmelCase__    ,    )["hidden_states"][0]

						# select random slice
						__SCREAMING_SNAKE_CASE		     =       ids_tensor((1,)    ,    output_from_past.shape[-1]     ).item()
						__SCREAMING_SNAKE_CASE		     =       output_from_no_past[:, -3:, random_slice_idx].detach()
						__SCREAMING_SNAKE_CASE		     =       output_from_past[:, :, random_slice_idx].detach()

						self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]     )

						# test that outputs are equal for slice
						self.parent.assertTrue(torch.allclose(UpperCAmelCase__    ,    UpperCAmelCase__    ,    atol=1E-3     )     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]    ,    UpperCAmelCase__    :       Any    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Tuple    ,    *UpperCAmelCase__    :       int    ,    ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationDecoder(UpperCAmelCase__     )
						model.to(UpperCAmelCase__     )
						model.eval()
						__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__    ,    attention_mask=UpperCAmelCase__    ,    labels=UpperCAmelCase__     )
						self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.seq_length, self.vocab_size)     )




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




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

	"""simple docstring"""





	snake_case__       :						List[str]					      =    (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else ()
	snake_case__       :						Dict					      =    (BertGenerationDecoder,) if is_torch_available() else ()
	snake_case__       :						List[Any]					      =    (
	    {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder}
	    if is_torch_available()
	    else {}
	)




	def 						UpperCAmelCase_   (				self    :       str     ) ->			Dict:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationEncoderTester(self     )
						__SCREAMING_SNAKE_CASE		     =       ConfigTester(self    ,    config_class=UpperCAmelCase__    ,    hidden_size=3_7     )




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			List[str]:
						self.config_tester.run_common_tests()




	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			str:
						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE     ,						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs()
						__SCREAMING_SNAKE_CASE		     =       "bert"
						self.model_tester.create_and_check_model(UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			Optional[Any]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Dict     ) ->			Tuple:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_decoder_model_past_large_inputs(*UpperCAmelCase__     )




	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			List[str]:
						# This regression test was failing with PyTorch < 1.3
						(
						    (
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,						(
						    __SCREAMING_SNAKE_CASE						
						)     ,												
						)		     =       self.model_tester.prepare_config_and_inputs_for_decoder()

						__SCREAMING_SNAKE_CASE		     =       None

						self.model_tester.create_and_check_model_as_decoder(
						    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    UpperCAmelCase__    ,    )




	def 						UpperCAmelCase_   (				self    :       Union[str, Any]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       self.model_tester.prepare_config_and_inputs_for_decoder()
						self.model_tester.create_and_check_for_causal_lm(*UpperCAmelCase__     )




	@slow
	def 						UpperCAmelCase_   (				self    :       Any     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"     )
						self.assertIsNotNone(UpperCAmelCase__     )




@require_torch
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	@slow
	def 						UpperCAmelCase_   (				self    :       Any     ) ->			List[str]:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationEncoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"     )
						__SCREAMING_SNAKE_CASE		     =       torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]     )
						with torch.no_grad():
											__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )[0]
						__SCREAMING_SNAKE_CASE		     =       torch.Size([1, 8, 1_0_2_4]     )
						self.assertEqual(output.shape    ,    UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       torch.tensor(
						    [[[0.1_775, 0.0_083, -0.0_321], [1.6_002, 0.1_287, 0.3_912], [2.1_473, 0.5_791, 0.6_066]]]     )
						self.assertTrue(torch.allclose(output[:, :3, :3]    ,    UpperCAmelCase__    ,    atol=1E-4     )     )




@require_torch
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	@slow
	def 						UpperCAmelCase_   (				self    :       str     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       BertGenerationDecoder.from_pretrained("google/bert_for_seq_generation_L-24_bbc_encoder"     )
						__SCREAMING_SNAKE_CASE		     =       torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]]     )
						with torch.no_grad():
											__SCREAMING_SNAKE_CASE		     =       model(UpperCAmelCase__     )[0]
						__SCREAMING_SNAKE_CASE		     =       torch.Size([1, 8, 5_0_3_5_8]     )
						self.assertEqual(output.shape    ,    UpperCAmelCase__     )
						__SCREAMING_SNAKE_CASE		     =       torch.tensor(
						    [[[-0.5_788, -2.5_994, -3.7_054], [0.0_438, 4.7_997, 1.8_795], [1.5_862, 6.6_409, 4.4_638]]]     )
						self.assertTrue(torch.allclose(output[:, :3, :3]    ,    UpperCAmelCase__    ,    atol=1E-4     )     )









"""simple docstring"""







import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
		from PIL import Image
else:




		class 				UpperCamelCase_			:

			"""simple docstring"""





			@staticmethod
			def 						UpperCAmelCase_   (				*UpperCAmelCase__    :       List[Any]    ,    **UpperCAmelCase__    :       Optional[Any]     ) ->			Optional[int]:
								pass




@is_pipeline_test
@require_torch
@require_vision
class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						List[Any]					      =    MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       Tuple    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Optional[int]     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="hf-internal-testing/tiny-vilt-random-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       [
						    {
						        "image": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"     ),
						        "question": "How many cats are there?",
						    },
						    {
						        "image": "./tests/fixtures/tests_samples/COCO/000000039769.png",
						        "question": "How many cats are there?",
						    },
						]
						return vqa_pipeline, examples




	def 						UpperCAmelCase_   (				self    :       Dict    ,    UpperCAmelCase__    :       List[Any]    ,    UpperCAmelCase__    :       Any     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(UpperCAmelCase__    ,    top_k=1     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [
						        [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}],
						        [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}],
						    ]    ,    )




	@require_torch
	def 						UpperCAmelCase_   (				self    :       Optional[Any]     ) ->			int:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="hf-internal-testing/tiny-vilt-random-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
						__SCREAMING_SNAKE_CASE		     =       "How many cats are there?"

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(image=UpperCAmelCase__    ,    question="How many cats are there?"    ,    top_k=2     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}, {"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline({"image": image, "question": question}    ,    top_k=2     )
						self.assertEqual(
						    UpperCAmelCase__    ,    [{"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}, {"score": ANY(UpperCAmelCase__     ), "answer": ANY(UpperCAmelCase__     )}]     )




	@slow
	@require_torch
	def 						UpperCAmelCase_   (				self    :       Tuple     ) ->			Any:
						__SCREAMING_SNAKE_CASE		     =       pipeline("visual-question-answering"    ,    model="dandelin/vilt-b32-finetuned-vqa"     )
						__SCREAMING_SNAKE_CASE		     =       "./tests/fixtures/tests_samples/COCO/000000039769.png"
						__SCREAMING_SNAKE_CASE		     =       "How many cats are there?"

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(image=UpperCAmelCase__    ,    question=UpperCAmelCase__    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline({"image": image, "question": question}    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]     )

						__SCREAMING_SNAKE_CASE		     =       vqa_pipeline(
						    [{"image": image, "question": question}, {"image": image, "question": question}]    ,    top_k=2     )
						self.assertEqual(
						    nested_simplify(UpperCAmelCase__    ,    decimals=4     )    ,    [[{"score": 0.8_799, "answer": "2"}, {"score": 0.296, "answer": "1"}]] * 2    ,    )




	@require_tf
	@unittest.skip("Visual question answering not implemented in TF"     )
	def 						UpperCAmelCase_   (				self    :       str     ) ->			Optional[Any]:
						pass
