


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 ,       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 ,       )  ->	List[str]:
         __UpperCamelCase   							=parent
         __UpperCamelCase   							=batch_size
         __UpperCamelCase   							=decoder_seq_length
         # For common tests
         __UpperCamelCase   							=self.decoder_seq_length
         __UpperCamelCase   							=is_training
         __UpperCamelCase   							=use_attention_mask
         __UpperCamelCase   							=use_labels

         __UpperCamelCase   							=vocab_size
         __UpperCamelCase   							=d_model
         __UpperCamelCase   							=d_model
         __UpperCamelCase   							=decoder_layers
         __UpperCamelCase   							=decoder_layers
         __UpperCamelCase   							=decoder_ffn_dim
         __UpperCamelCase   							=decoder_attention_heads
         __UpperCamelCase   							=decoder_attention_heads
         __UpperCamelCase   							=eos_token_id
         __UpperCamelCase   							=bos_token_id
         __UpperCamelCase   							=pad_token_id
         __UpperCamelCase   							=decoder_start_token_id
         __UpperCamelCase   							=use_cache
         __UpperCamelCase   							=max_position_embeddings

         __UpperCamelCase   							=None
         __UpperCamelCase   							=decoder_seq_length
         __UpperCamelCase   							=2
         __UpperCamelCase   							=1






    def _a (      self   )  ->	List[Any]:
         __UpperCamelCase   							=ids_tensor([self.batch_size, self.decoder_seq_length] ,       self.vocab_size   )

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

         __UpperCamelCase   							=None
         if self.use_labels:
              __UpperCamelCase   							=ids_tensor([self.batch_size, self.decoder_seq_length] ,       self.vocab_size   )

         __UpperCamelCase   							=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_ ,       )  ->	Dict:
         __UpperCamelCase   							=True
         __UpperCamelCase   							=TrOCRDecoder(config=A_   ).to(A_   ).eval()
         __UpperCamelCase   							=input_ids[:2]

         input_ids[input_ids == 0] += 1
         # first forward pass
         __UpperCamelCase   							=model(A_ ,       use_cache=A_   )
         __UpperCamelCase   							=model(A_   )
         __UpperCamelCase   							=model(A_ ,       use_cache=A_   )

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

         __UpperCamelCase   							=outputs['past_key_values']

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

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

         __UpperCamelCase   							=model(A_   )['last_hidden_state']
         __UpperCamelCase   							=model(A_ ,       past_key_values=A_   )['last_hidden_state']

         # select random slice
         __UpperCamelCase   							=ids_tensor((1,) ,       output_from_past.shape[-1]   ).item()
         __UpperCamelCase   							=output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
         __UpperCamelCase   							=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   )  ->	Union[str, Any]:
         __UpperCamelCase   							=self.prepare_config_and_inputs()
         __UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase							,				__UpperCamelCase   							=config_and_inputs

         __UpperCamelCase   							={'input_ids': input_ids, 'attention_mask': attention_mask}
         return config, inputs_dict






@require_torch
class    UpperCAmelCase__	( A_       ,  A_       ,  A_       ,  unittest.TestCase		):



    """simple docstring"""






    UpperCAmelCase__						:		Optional[Any]              =  (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
    UpperCAmelCase__						:		str              =  (TrOCRForCausalLM,) if is_torch_available() else ()
    UpperCAmelCase__						:		Dict              =  {"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
    UpperCAmelCase__						:		Union[str, Any]              =  True
    UpperCAmelCase__						:		Tuple              =  False






    def _a (      self   )  ->	Optional[Any]:
         __UpperCamelCase   							=TrOCRStandaloneDecoderModelTester(self ,       is_training=A_   )
         __UpperCamelCase   							=ConfigTester(self ,       config_class=A_   )






    def _a (      self   )  ->	List[str]:
         pass






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






    def _a (      self   )  ->	Union[str, Any]:
         pass






    def _a (      self   )  ->	Tuple:
         self.config_tester.run_common_tests()






    def _a (      self   )  ->	Optional[int]:
         __UpperCamelCase   							=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_decoder_model_past(*A_   )






    def _a (      self   )  ->	int:
         return






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









from __future__ import annotations

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int    ):
     if b == 0:
          return (1, 0)
     ((__UpperCamelCase)							,				(__UpperCamelCase))   							=extended_euclid(SCREAMING_SNAKE_CASE__      ,					a % b    )
     __UpperCamelCase   							=a // b
     return (y, x - k * y)

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int    ):
     ((__UpperCamelCase)							,				(__UpperCamelCase))   							=extended_euclid(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase   							=na * na
     __UpperCamelCase   							=ra * x * na + ra * y * na
     return (n % m + m) % m

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int    ):
     ((__UpperCamelCase)							,				(__UpperCamelCase))   							=extended_euclid(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )
     if b < 0:
          __UpperCamelCase   							=(b % n + n) % n
     return b

def 						_UpperCAmelCase    (      SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int      ,					SCREAMING_SNAKE_CASE__      : int    ):
     __UpperCamelCase							,				__UpperCamelCase   							=invert_modulo(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    ), invert_modulo(SCREAMING_SNAKE_CASE__      ,					SCREAMING_SNAKE_CASE__    )
     __UpperCamelCase   							=na * na
     __UpperCamelCase   							=ra * x * na + ra * y * na
     return (n % m + m) % m


if __name__ == "__main__":
   from doctest import testmod

   testmod(name='chinese_remainder_theorem', verbose=True)
   testmod(name='chinese_remainder_theorem2', verbose=True)
   testmod(name='invert_modulo', verbose=True)
   testmod(name='extended_euclid', verbose=True)





