

import unittest

from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

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


if is_torch_available():
			import torch

			from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM






@require_torch
class _UpperCamelCase							:
			'''simple docstring'''







			def __init__(	self							:       List[Any]					,					a							:       Optional[Any]					,					a							:       List[Any]=99					,					a							:       Union[str, Any]=13					,					a							:       List[str]=16					,					a							:       Tuple=7					,					a							:       Dict=True					,					a							:       List[str]=True					,					a							:       Union[str, Any]=True					,					a							:       Optional[int]=False					,					a							:       Union[str, Any]=True					,					a							:       List[str]=2					,					a							:       Dict=32					,					a							:       List[Any]=4					,					a							:       Optional[Any]=4					,					a							:       List[str]=30					,					a							:       str=0					,					a							:       str=1					,					a							:       Tuple=2					,					a							:       Optional[Any]=None					,					)							->				Optional[int]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Tuple    =				parent
				SCREAMING_SNAKE_CASE      :					Tuple    =				batch_size
				SCREAMING_SNAKE_CASE      :					Dict    =				decoder_seq_length
				# For common tests
				SCREAMING_SNAKE_CASE      :					Dict    =				self.decoder_seq_length
				SCREAMING_SNAKE_CASE      :					Tuple    =				is_training
				SCREAMING_SNAKE_CASE      :					int    =				use_attention_mask
				SCREAMING_SNAKE_CASE      :					str    =				use_labels

				SCREAMING_SNAKE_CASE      :					List[str]    =				vocab_size
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				d_model
				SCREAMING_SNAKE_CASE      :					List[Any]    =				d_model
				SCREAMING_SNAKE_CASE      :					Tuple    =				decoder_layers
				SCREAMING_SNAKE_CASE      :					Any    =				decoder_layers
				SCREAMING_SNAKE_CASE      :					Tuple    =				decoder_ffn_dim
				SCREAMING_SNAKE_CASE      :					int    =				decoder_attention_heads
				SCREAMING_SNAKE_CASE      :					int    =				decoder_attention_heads
				SCREAMING_SNAKE_CASE      :					Any    =				eos_token_id
				SCREAMING_SNAKE_CASE      :					int    =				bos_token_id
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				pad_token_id
				SCREAMING_SNAKE_CASE      :					str    =				decoder_start_token_id
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				use_cache
				SCREAMING_SNAKE_CASE      :					List[Any]    =				max_position_embeddings

				SCREAMING_SNAKE_CASE      :					int    =				None
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				decoder_seq_length
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				2
				SCREAMING_SNAKE_CASE      :					Tuple    =				1
			def 							__UpperCamelCase       (	self							:       Optional[int]		)							->				List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				ids_tensor([self.batch_size, self.decoder_seq_length]					,					self.vocab_size		)

				SCREAMING_SNAKE_CASE      :					List[Any]    =				None
				if self.use_attention_mask:
					SCREAMING_SNAKE_CASE      :					Optional[Any]    =				ids_tensor([self.batch_size, self.decoder_seq_length]					,					vocab_size=2		)

				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				None
				if self.use_labels:
					SCREAMING_SNAKE_CASE      :					List[Any]    =				ids_tensor([self.batch_size, self.decoder_seq_length]					,					self.vocab_size		)

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				TrOCRConfig(
				    vocab_size=self.vocab_size					,					d_model=self.d_model					,					decoder_layers=self.decoder_layers					,					decoder_ffn_dim=self.decoder_ffn_dim					,					decoder_attention_heads=self.decoder_attention_heads					,					eos_token_id=self.eos_token_id					,					bos_token_id=self.bos_token_id					,					use_cache=self.use_cache					,					pad_token_id=self.pad_token_id					,					decoder_start_token_id=self.decoder_start_token_id					,					max_position_embeddings=self.max_position_embeddings					,					)

				return (config, input_ids, attention_mask, lm_labels)
			def 							__UpperCamelCase       (	self							:       Tuple					,					a							:       Optional[Any]					,					a							:       int					,					a							:       Tuple					,					a							:       List[Any]					,					)							->				Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Optional[int]    =				True
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				TrOCRDecoder(config=a		).to(a		).eval()
				SCREAMING_SNAKE_CASE      :					Any    =				input_ids[:2]

				input_ids[input_ids == 0] += 1
				# first forward pass
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				model(a					,					use_cache=a		)
				SCREAMING_SNAKE_CASE      :					Tuple    =				model(a		)
				SCREAMING_SNAKE_CASE      :					Tuple    =				model(a					,					use_cache=a		)

				self.parent.assertTrue(len(a		) == len(a		)		)
				self.parent.assertTrue(len(a		) == len(a		) + 1		)

				SCREAMING_SNAKE_CASE      :					Any    =				outputs["past_key_values"]

				# create hypothetical next token and extent to next_input_ids
				SCREAMING_SNAKE_CASE      :					Optional[Any]    =				ids_tensor((2, 1)					,					config.vocab_size - 1		) + 1

				# append to next input_ids and
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				torch.cat([input_ids, next_tokens]					,					dim=-1		)

				SCREAMING_SNAKE_CASE      :					Any    =				model(a		)["last_hidden_state"]
				SCREAMING_SNAKE_CASE      :					List[str]    =				model(a					,					past_key_values=a		)["last_hidden_state"]

				# select random slice
				SCREAMING_SNAKE_CASE      :					Tuple    =				ids_tensor((1,)					,					output_from_past.shape[-1]		).item()
				SCREAMING_SNAKE_CASE      :					Optional[int]    =				output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				output_from_past[:, 0, random_slice_idx].detach()

				# test that outputs are equal for slice
				assert torch.allclose(a					,					a					,					atol=1e-3		)






			def 							__UpperCamelCase       (	self							:       Dict		)							->				Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE   ,SCREAMING_SNAKE_CASE      :					Optional[Any]    =				config_and_inputs

				SCREAMING_SNAKE_CASE      :					Tuple    =				{"input_ids": input_ids, "attention_mask": attention_mask}
				return config, inputs_dict






@require_torch
class _UpperCamelCase							(							__A							,		__A							,		__A							,		unittest.TestCase      ):
			'''simple docstring'''







			lowerCamelCase__							=(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
			lowerCamelCase__							=(TrOCRForCausalLM,) if is_torch_available() else ()
			lowerCamelCase__							={'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
			lowerCamelCase__							=True
			lowerCamelCase__							=False
			def 							__UpperCamelCase       (	self							:       int		)							->				int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Union[str, Any]    =				TrOCRStandaloneDecoderModelTester(self					,					is_training=a		)
				SCREAMING_SNAKE_CASE      :					str    =				ConfigTester(self					,					config_class=a		)
			def 							__UpperCamelCase       (	self							:       Optional[int]		)							->				str:

				"""simple docstring"""

				pass
			def 							__UpperCamelCase       (	self							:       Dict		)							->				Any:

				"""simple docstring"""

				pass
			def 							__UpperCamelCase       (	self							:       Optional[Any]		)							->				Tuple:

				"""simple docstring"""

				pass
			def 							__UpperCamelCase       (	self							:       Tuple		)							->				List[Any]:

				"""simple docstring"""

				self.config_tester.run_common_tests()
			def 							__UpperCamelCase       (	self							:       int		)							->				Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE      :					Any    =				self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_decoder_model_past(*a		)
			def 							__UpperCamelCase       (	self							:       List[Any]		)							->				Any:

				"""simple docstring"""

				return






			@unittest.skip("The model doesn't support left padding"		)  # and it's not used enough to be worth fixing :)
			def 							__UpperCamelCase       (	self							:       List[str]		)							->				int:

				"""simple docstring"""

				pass

'''simple docstring'''




import os
import sys
import unittest


lowercase			:				Dict    		=			os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))

import get_test_info  # noqa: E402
from get_test_info import (  # noqa: E402
    get_model_to_test_mapping,
    get_model_to_tester_mapping,
    get_test_to_tester_mapping,
)


lowercase			:				Any    		=			os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py')
lowercase			:				Optional[int]    		=			os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py')





class  A				(							unittest.TestCase						):





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         A       :   Tuple					=						get_test_to_tester_mapping(SCREAMING_SNAKE_CASE	)
         A       :   Any					=						get_test_to_tester_mapping(SCREAMING_SNAKE_CASE	)

         A       :   List[Any]					=						{'''BertModelTest''': '''BertModelTester'''}

         A       :   int					=						{
             '''BlipModelTest''': '''BlipModelTester''',
             '''BlipTextImageModelTest''': '''BlipTextImageModelsModelTester''',
             '''BlipTextModelTest''': '''BlipTextModelTester''',
             '''BlipTextRetrievalModelTest''': '''BlipTextRetrievalModelTester''',
             '''BlipVQAModelTest''': '''BlipVQAModelTester''',
             '''BlipVisionModelTest''': '''BlipVisionModelTester''',
         }

         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)
         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Any:






         """simple docstring"""






         A       :   Tuple					=						get_model_to_test_mapping(SCREAMING_SNAKE_CASE	)
         A       :   Tuple					=						get_model_to_test_mapping(SCREAMING_SNAKE_CASE	)

         A       :   List[str]					=						{
             '''BertForMaskedLM''': ['''BertModelTest'''],
             '''BertForMultipleChoice''': ['''BertModelTest'''],
             '''BertForNextSentencePrediction''': ['''BertModelTest'''],
             '''BertForPreTraining''': ['''BertModelTest'''],
             '''BertForQuestionAnswering''': ['''BertModelTest'''],
             '''BertForSequenceClassification''': ['''BertModelTest'''],
             '''BertForTokenClassification''': ['''BertModelTest'''],
             '''BertLMHeadModel''': ['''BertModelTest'''],
             '''BertModel''': ['''BertModelTest'''],
         }

         A       :   Union[str, Any]					=						{
             '''BlipForConditionalGeneration''': ['''BlipTextImageModelTest'''],
             '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTest'''],
             '''BlipForQuestionAnswering''': ['''BlipVQAModelTest'''],
             '''BlipModel''': ['''BlipModelTest'''],
             '''BlipTextModel''': ['''BlipTextModelTest'''],
             '''BlipVisionModel''': ['''BlipVisionModelTest'''],
         }

         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)
         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   int					=						get_model_to_tester_mapping(SCREAMING_SNAKE_CASE	)
         A       :   Union[str, Any]					=						get_model_to_tester_mapping(SCREAMING_SNAKE_CASE	)

         A       :   Dict					=						{
             '''BertForMaskedLM''': ['''BertModelTester'''],
             '''BertForMultipleChoice''': ['''BertModelTester'''],
             '''BertForNextSentencePrediction''': ['''BertModelTester'''],
             '''BertForPreTraining''': ['''BertModelTester'''],
             '''BertForQuestionAnswering''': ['''BertModelTester'''],
             '''BertForSequenceClassification''': ['''BertModelTester'''],
             '''BertForTokenClassification''': ['''BertModelTester'''],
             '''BertLMHeadModel''': ['''BertModelTester'''],
             '''BertModel''': ['''BertModelTester'''],
         }

         A       :   str					=						{
             '''BlipForConditionalGeneration''': ['''BlipTextImageModelsModelTester'''],
             '''BlipForImageTextRetrieval''': ['''BlipTextRetrievalModelTester'''],
             '''BlipForQuestionAnswering''': ['''BlipVQAModelTester'''],
             '''BlipModel''': ['''BlipModelTester'''],
             '''BlipTextModel''': ['''BlipTextModelTester'''],
             '''BlipVisionModel''': ['''BlipVisionModelTester'''],
         }

         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)
         self.assertEqual(get_test_info.to_json(SCREAMING_SNAKE_CASE	)						,			SCREAMING_SNAKE_CASE	)




