'''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        A__				:





   """simple docstring"""





   def __init__(					self	:						Union[str, Any]		,	lowerCAmelCase__	:						int		,	lowerCAmelCase__	:						Dict=9_9		,	lowerCAmelCase__	:						Optional[Any]=1_3		,	lowerCAmelCase__	:						Any=1_6		,	lowerCAmelCase__	:						List[Any]=7		,	lowerCAmelCase__	:						List[str]=True		,	lowerCAmelCase__	:						Dict=True		,	lowerCAmelCase__	:						Dict=True		,	lowerCAmelCase__	:						Tuple=False		,	lowerCAmelCase__	:						Any=True		,	lowerCAmelCase__	:						str=2		,	lowerCAmelCase__	:						Tuple=3_2		,	lowerCAmelCase__	:						str=4		,	lowerCAmelCase__	:						str=4		,	lowerCAmelCase__	:						Optional[int]=3_0		,	lowerCAmelCase__	:						List[str]=0		,	lowerCAmelCase__	:						Tuple=1		,	lowerCAmelCase__	:						int=2		,	lowerCAmelCase__	:						List[str]=None		,	)			->       Any:







      """simple docstring"""




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

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

      _UpperCAmelCase				:      List[str]				=  None
      _UpperCAmelCase				:      Dict				=  decoder_seq_length
      _UpperCAmelCase				:      List[Any]				=  2
      _UpperCAmelCase				:      List[str]				=  1




   def      _lowerCAmelCase						(					self	:						Union[str, Any]     )			->       List[str]:







      """simple docstring"""




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

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

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

      _UpperCAmelCase				:      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      _lowerCAmelCase						(					self	:						Tuple		,	lowerCAmelCase__	:						Any		,	lowerCAmelCase__	:						Tuple		,	lowerCAmelCase__	:						Any		,	lowerCAmelCase__	:						Optional[int]		,	)			->       List[str]:







      """simple docstring"""




      _UpperCAmelCase				:      Union[str, Any]				=  True
      _UpperCAmelCase				:      Any				=  TrOCRDecoder(config=lowerCamelCase__     ).to(lowerCamelCase__     ).eval()
      _UpperCAmelCase				:      List[Any]				=  input_ids[:2]

      input_ids[input_ids == 0] += 1
      # first forward pass
      _UpperCAmelCase				:      Dict				=  model(lowerCamelCase__		,	use_cache=lowerCamelCase__     )
      _UpperCAmelCase				:      int				=  model(lowerCamelCase__     )
      _UpperCAmelCase				:      List[Any]				=  model(lowerCamelCase__		,	use_cache=lowerCamelCase__     )

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

      _UpperCAmelCase				:      Optional[int]				=  outputs['past_key_values']

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

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

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

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

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




   def      _lowerCAmelCase						(					self	:						List[str]     )			->       int:







      """simple docstring"""




      _UpperCAmelCase				:      List[str]				=  self.prepare_config_and_inputs()
      _UpperCAmelCase				:      List[Any]				=  config_and_inputs

      _UpperCAmelCase				:      str				=  {'input_ids': input_ids, 'attention_mask': attention_mask}
      return config, inputs_dict





@require_torch
class        A__				(			UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase   ,						unittest.TestCase  ):





   """simple docstring"""





   UpperCamelCase_			:		Tuple       							=	(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
   UpperCamelCase_			:		Union[str, Any]       							=	(TrOCRForCausalLM,) if is_torch_available() else ()
   UpperCamelCase_			:		Any       							=	{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
   UpperCamelCase_			:		List[str]       							=	True
   UpperCamelCase_			:		Union[str, Any]       							=	False




   def      _lowerCAmelCase						(					self	:						str     )			->       Any:







      """simple docstring"""




      _UpperCAmelCase				:      Dict				=  TrOCRStandaloneDecoderModelTester(self		,	is_training=lowerCamelCase__     )
      _UpperCAmelCase				:      Dict				=  ConfigTester(self		,	config_class=lowerCamelCase__     )




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







      """simple docstring"""




      pass




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







      """simple docstring"""




      pass




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







      """simple docstring"""




      pass




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







      """simple docstring"""




      self.config_tester.run_common_tests()




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







      """simple docstring"""




      _UpperCAmelCase				:      Dict				=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase__     )




   def      _lowerCAmelCase						(					self	:						Optional[int]     )			->       Optional[Any]:







      """simple docstring"""




      return




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







      """simple docstring"""




      pass




'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


snake_case_					:      Tuple    			=    {
    'configuration_layoutlmv2': ['LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv2Config'],
    'processing_layoutlmv2': ['LayoutLMv2Processor'],
    'tokenization_layoutlmv2': ['LayoutLMv2Tokenizer'],
}

try:
					if not is_tokenizers_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					snake_case_					:      int    			=    ['LayoutLMv2TokenizerFast']

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					snake_case_					:      Union[str, Any]    			=    ['LayoutLMv2FeatureExtractor']
					snake_case_					:      str    			=    ['LayoutLMv2ImageProcessor']

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					snake_case_					:      Optional[int]    			=    [
					    'LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST',
					    'LayoutLMv2ForQuestionAnswering',
					    'LayoutLMv2ForSequenceClassification',
					    'LayoutLMv2ForTokenClassification',
					    'LayoutLMv2Layer',
					    'LayoutLMv2Model',
					    'LayoutLMv2PreTrainedModel',
					]

if TYPE_CHECKING:
					from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
					from .processing_layoutlmva import LayoutLMvaProcessor
					from .tokenization_layoutlmva import LayoutLMvaTokenizer

					try:
										if not is_tokenizers_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_layoutlmva import (
										    LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
										    LayoutLMvaForQuestionAnswering,
										    LayoutLMvaForSequenceClassification,
										    LayoutLMvaForTokenClassification,
										    LayoutLMvaLayer,
										    LayoutLMvaModel,
										    LayoutLMvaPreTrainedModel,
										)
else:
					import sys

					snake_case_					:      int    			=    _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


