


"""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 				SCREAMING_SNAKE_CASE__    :
       """simple docstring"""


       def __init__(						self		,					snake_case__		,					snake_case__=99		,					snake_case__=13		,					snake_case__=16		,					snake_case__=7		,					snake_case__=True		,					snake_case__=True		,					snake_case__=True		,					snake_case__=False		,					snake_case__=True		,					snake_case__=2		,					snake_case__=32		,					snake_case__=4		,					snake_case__=4		,					snake_case__=30		,					snake_case__=0		,					snake_case__=1		,					snake_case__=2		,					snake_case__=None		,					):






         """simple docstring"""





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

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

         lowerCAmelCase					:					Tuple								=							None
         lowerCAmelCase					:					Any								=							decoder_seq_length
         lowerCAmelCase					:					int								=							2
         lowerCAmelCase					:					Dict								=							1

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Union[str, Any]								=							ids_tensor([self.batch_size, self.decoder_seq_length]		,					self.vocab_size						)

         lowerCAmelCase					:					Union[str, Any]								=							None
         if self.use_attention_mask:
           lowerCAmelCase					:					str								=							ids_tensor([self.batch_size, self.decoder_seq_length]		,					vocab_size=2						)

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

         lowerCAmelCase					:					List[str]								=							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 	lowercase__							(						self		,					snake_case__		,					snake_case__		,					snake_case__		,					snake_case__		,					):






         """simple docstring"""





         lowerCAmelCase					:					Optional[int]								=							True
         lowerCAmelCase					:					List[Any]								=							TrOCRDecoder(config=_UpperCAmelCase						).to(_UpperCAmelCase						).eval()
         lowerCAmelCase					:					List[Any]								=							input_ids[:2]

         input_ids[input_ids == 0] += 1
         # first forward pass
         lowerCAmelCase					:					List[str]								=							model(_UpperCAmelCase		,					use_cache=_UpperCAmelCase						)
         lowerCAmelCase					:					Union[str, Any]								=							model(_UpperCAmelCase						)
         lowerCAmelCase					:					Optional[int]								=							model(_UpperCAmelCase		,					use_cache=_UpperCAmelCase						)

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

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

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

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

         lowerCAmelCase					:					int								=							model(_UpperCAmelCase						)['''last_hidden_state''']
         lowerCAmelCase					:					List[str]								=							model(_UpperCAmelCase		,					past_key_values=_UpperCAmelCase						)['''last_hidden_state''']

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

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







       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Optional[int]								=							self.prepare_config_and_inputs()
         lowerCAmelCase					:					int								=							config_and_inputs

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


@require_torch
class 				SCREAMING_SNAKE_CASE__    (		_UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   unittest.TestCase    ):
       """simple docstring"""


       a  :    List[Any]       =(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
       a  :    Optional[Any]       =(TrOCRForCausalLM,) if is_torch_available() else ()
       a  :    int       ={"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
       a  :    int       =True
       a  :    Any       =False

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					List[str]								=							TrOCRStandaloneDecoderModelTester(self		,					is_training=_UpperCAmelCase						)
         lowerCAmelCase					:					Optional[int]								=							ConfigTester(self		,					config_class=_UpperCAmelCase						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         pass

       def 	lowercase__							(						self						):






         """simple docstring"""





         pass

       def 	lowercase__							(						self						):






         """simple docstring"""





         pass

       def 	lowercase__							(						self						):






         """simple docstring"""





         self.config_tester.run_common_tests()

       def 	lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase					:					Tuple								=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_decoder_model_past(*_UpperCAmelCase						)

       def 	lowercase__							(						self						):






         """simple docstring"""





         return







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






         """simple docstring"""





         pass









"""simple docstring"""







from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


lowerCAmelCase__				    =       {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']}


try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCAmelCase__				    =       [
         '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''',
         '''VanForImageClassification''',
         '''VanModel''',
         '''VanPreTrainedModel''',
     ]

if TYPE_CHECKING:
     from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_van import (
              VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
              VanForImageClassification,
              VanModel,
              VanPreTrainedModel,
          )

else:
     import sys

     lowerCAmelCase__				    =       _LazyModule(__name__, globals()['''__file__'''], _import_structure)





