






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__ :







		def __init__(					self       ,A__       ,A__=99       ,A__=13       ,A__=16       ,A__=7       ,A__=True       ,A__=True       ,A__=True       ,A__=False       ,A__=True       ,A__=2       ,A__=32       ,A__=4       ,A__=4       ,A__=30       ,A__=0       ,A__=1       ,A__=2       ,A__=None       ,):
						_A	:				Dict   =      parent
						_A	:				Optional[Any]   =      batch_size
						_A	:				int   =      decoder_seq_length
						# For common tests
						_A	:				Optional[Any]   =      self.decoder_seq_length
						_A	:				int   =      is_training
						_A	:				Optional[Any]   =      use_attention_mask
						_A	:				Dict   =      use_labels

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

						_A	:				Tuple   =      None
						_A	:				str   =      decoder_seq_length
						_A	:				List[Any]   =      2
						_A	:				Any   =      1







		def  A__      (					self		):
						_A	:				Optional[int]   =      ids_tensor([self.batch_size, self.decoder_seq_length]       ,self.vocab_size		)

						_A	:				int   =      None
						if self.use_attention_mask:
										_A	:				str   =      ids_tensor([self.batch_size, self.decoder_seq_length]       ,vocab_size=2		)

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

						_A	:				Dict   =      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  A__      (					self       ,A__       ,A__       ,A__       ,A__       ,):
						_A	:				int   =      True
						_A	:				str   =      TrOCRDecoder(config=A__		).to(A__		).eval()
						_A	:				Union[str, Any]   =      input_ids[:2]

						input_ids[input_ids == 0] += 1
						# first forward pass
						_A	:				List[Any]   =      model(A__       ,use_cache=A__		)
						_A	:				List[Any]   =      model(A__		)
						_A	:				Any   =      model(A__       ,use_cache=A__		)

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

						_A	:				List[Any]   =      outputs['''past_key_values''']

						# create hypothetical next token and extent to next_input_ids
						_A	:				str   =      ids_tensor((2, 1)       ,config.vocab_size - 1		) + 1

						# append to next input_ids and
						_A	:				Optional[int]   =      torch.cat([input_ids, next_tokens]       ,dim=-1		)

						_A	:				int   =      model(A__		)['''last_hidden_state''']
						_A	:				int   =      model(A__       ,past_key_values=A__		)['''last_hidden_state''']

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

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







		def  A__      (					self		):
						_A	:				List[Any]   =      self.prepare_config_and_inputs()
						_A  ,				_A  ,				_A  ,				_A	:				str   =      config_and_inputs

						_A	:				Tuple   =      {'''input_ids''': input_ids, '''attention_mask''': attention_mask}
						return config, inputs_dict






@require_torch
class 						UpperCAmelCase__ (							__snake_case     ,				__snake_case     ,				__snake_case     ,				unittest.TestCase							):
		__snake_case      :       Dict     =   (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
		__snake_case      :       List[Any]     =   (TrOCRForCausalLM,) if is_torch_available() else ()
		__snake_case      :       Optional[int]     =   {"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
		__snake_case      :       Any     =   True
		__snake_case      :       Optional[Any]     =   False







		def  A__      (					self		):
						_A	:				Optional[Any]   =      TrOCRStandaloneDecoderModelTester(self       ,is_training=A__		)
						_A	:				int   =      ConfigTester(self       ,config_class=A__		)







		def  A__      (					self		):
						pass







		def  A__      (					self		):
						pass







		def  A__      (					self		):
						pass







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







		def  A__      (					self		):
						_A	:				List[Any]   =      self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_decoder_model_past(*A__		)







		def  A__      (					self		):
						return







		@unittest.skip('''The model doesn\'t support left padding'''		)  # and it's not used enough to be worth fixing :)
		def  A__      (					self		):
						pass











def  a__ (__lowercase							:int					,  __lowercase							:int   )		-> int:
				return abs(__lowercase   ) if a == 0 else greatest_common_divisor(b % a					,  __lowercase   )



def  a__ (__lowercase							:int					,  __lowercase							:int   )		-> int:
				while y:  # --> when y=0 then loop will terminate and return x as final GCD.
								_A  ,				_A	:				Union[str, Any]   =      y, x % y
				return abs(__lowercase   )



def  a__ ()		-> Optional[Any]:
				try:
								_A	:				Optional[Any]   =      input('''Enter two integers separated by comma (,): '''   ).split(''','''   )
								_A	:				List[Any]   =      int(nums[0]   )
								_A	:				Optional[int]   =      int(nums[1]   )
								print(
								    f"""greatest_common_divisor({num_a}, {num_a}) = """
								    f"""{greatest_common_divisor(__lowercase					,  __lowercase   )}"""   )
								print(f"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(__lowercase					,  __lowercase   )}"""   )
				except (IndexError, UnboundLocalError, ValueError):
								print('''Wrong input'''   )


if __name__ == "__main__":
	main()



