






'''simple docstring'''



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      :		Optional[int]  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Optional[int]=99  ,   UpperCAmelCase      :		Optional[Any]=13  ,   UpperCAmelCase      :		str=16  ,   UpperCAmelCase      :		Union[str, Any]=7  ,   UpperCAmelCase      :		str=True  ,   UpperCAmelCase      :		Union[str, Any]=True  ,   UpperCAmelCase      :		Union[str, Any]=True  ,   UpperCAmelCase      :		List[Any]=False  ,   UpperCAmelCase      :		Dict=True  ,   UpperCAmelCase      :		Any=2  ,   UpperCAmelCase      :		Optional[int]=32  ,   UpperCAmelCase      :		List[str]=4  ,   UpperCAmelCase      :		Optional[Any]=4  ,   UpperCAmelCase      :		Tuple=30  ,   UpperCAmelCase      :		Union[str, Any]=0  ,   UpperCAmelCase      :		Any=1  ,   UpperCAmelCase      :		int=2  ,   UpperCAmelCase      :		Optional[Any]=None  ,   )	->	Dict:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=parent
       lowercase       : str						=batch_size
       lowercase       : Optional[Any]						=decoder_seq_length
       # For common tests
       lowercase       : List[Any]						=self.decoder_seq_length
       lowercase       : int						=is_training
       lowercase       : int						=use_attention_mask
       lowercase       : Optional[Any]						=use_labels

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

       lowercase       : Optional[Any]						=None
       lowercase       : Optional[Any]						=decoder_seq_length
       lowercase       : Optional[Any]						=2
       lowercase       : Optional[int]						=1






      def 					A__   (			self      :		Dict		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Optional[Any]						=ids_tensor([self.batch_size, self.decoder_seq_length]  ,   self.vocab_size		)

       lowercase       : List[str]						=None
       if self.use_attention_mask:
        lowercase       : Tuple						=ids_tensor([self.batch_size, self.decoder_seq_length]  ,   vocab_size=2		)

       lowercase       : str						=None
       if self.use_labels:
        lowercase       : Union[str, Any]						=ids_tensor([self.batch_size, self.decoder_seq_length]  ,   self.vocab_size		)

       lowercase       : 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      :		Dict  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Optional[int]  ,   )	->	int:


       '''simple docstring'''

       lowercase       : Optional[int]						=True
       lowercase       : Optional[Any]						=TrOCRDecoder(config=UpperCAmelCase		).to(UpperCAmelCase		).eval()
       lowercase       : str						=input_ids[:2]

       input_ids[input_ids == 0] += 1
       # first forward pass
       lowercase       : Dict						=model(UpperCAmelCase  ,   use_cache=UpperCAmelCase		)
       lowercase       : List[str]						=model(UpperCAmelCase		)
       lowercase       : Any						=model(UpperCAmelCase  ,   use_cache=UpperCAmelCase		)

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

       lowercase       : Any						=outputs['''past_key_values''']

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

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

       lowercase       : Union[str, Any]						=model(UpperCAmelCase		)['''last_hidden_state''']
       lowercase       : str						=model(UpperCAmelCase  ,   past_key_values=UpperCAmelCase		)['''last_hidden_state''']

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

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






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


       '''simple docstring'''

       lowercase       : Dict						=self.prepare_config_and_inputs()
       lowercase	,		lowercase	,		lowercase	,		lowercase       : Union[str, Any]						=config_and_inputs

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





@require_torch
class UpperCAmelCase_       (     __A					,							__A					,							__A					,							unittest.TestCase					):




      """simple docstring"""




      UpperCamelCase_             =      (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
      UpperCamelCase_             =      (TrOCRForCausalLM,) if is_torch_available() else ()
      UpperCamelCase_             =      {'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
      UpperCamelCase_             =      True
      UpperCamelCase_             =      False






      def 					A__   (			self      :		Any		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=TrOCRStandaloneDecoderModelTester(self  ,   is_training=UpperCAmelCase		)
       lowercase       : List[str]						=ConfigTester(self  ,   config_class=UpperCAmelCase		)






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


       '''simple docstring'''

       pass






      def 					A__   (			self      :		int		)	->	Tuple:


       '''simple docstring'''

       pass






      def 					A__   (			self      :		Optional[Any]		)	->	Optional[Any]:


       '''simple docstring'''

       pass






      def 					A__   (			self      :		str		)	->	Tuple:


       '''simple docstring'''

       self.config_tester.run_common_tests()






      def 					A__   (			self      :		List[str]		)	->	Any:


       '''simple docstring'''

       lowercase       : str						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_decoder_model_past(*UpperCAmelCase		)






      def 					A__   (			self      :		str		)	->	int:


       '''simple docstring'''

       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]		)	->	int:


       '''simple docstring'''

       pass






from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
   if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ...utils.dummy_torch_and_transformers_objects import (
       VersatileDiffusionDualGuidedPipeline,
       VersatileDiffusionImageVariationPipeline,
       VersatileDiffusionPipeline,
       VersatileDiffusionTextToImagePipeline,
   )
else:
   from .modeling_text_unet import UNetFlatConditionModel
   from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
   from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
   from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
   from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline


