






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


 def __init__(     self		:						str							,						UpperCAmelCase__		:						Dict							,						UpperCAmelCase__		:						Any=99							,						UpperCAmelCase__		:						Tuple=13							,						UpperCAmelCase__		:						int=16							,						UpperCAmelCase__		:						Union[str, Any]=7							,						UpperCAmelCase__		:						List[str]=True							,						UpperCAmelCase__		:						Dict=True							,						UpperCAmelCase__		:						Union[str, Any]=True							,						UpperCAmelCase__		:						Optional[Any]=False							,						UpperCAmelCase__		:						str=True							,						UpperCAmelCase__		:						int=2							,						UpperCAmelCase__		:						str=32							,						UpperCAmelCase__		:						List[Any]=4							,						UpperCAmelCase__		:						List[str]=4							,						UpperCAmelCase__		:						str=30							,						UpperCAmelCase__		:						Any=0							,						UpperCAmelCase__		:						str=1							,						UpperCAmelCase__		:						Any=2							,						UpperCAmelCase__		:						Optional[Any]=None							,						)					->       Any:
   _a  :       str             =	parent
   _a  :       List[Any]             =	batch_size
   _a  :       Optional[Any]             =	decoder_seq_length
   # For common tests
   _a  :       List[Any]             =	self.decoder_seq_length
   _a  :       Optional[int]             =	is_training
   _a  :       Tuple             =	use_attention_mask
   _a  :       int             =	use_labels

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

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


 def _lowercase	(     self		:						Tuple							)					->       Optional[int]:
   _a  :       Optional[Any]             =	ids_tensor([self.batch_size, self.decoder_seq_length]							,						self.vocab_size							)

   _a  :       Dict             =	None
   if self.use_attention_mask:
     _a  :       Optional[int]             =	ids_tensor([self.batch_size, self.decoder_seq_length]							,						vocab_size=2							)

   _a  :       str             =	None
   if self.use_labels:
     _a  :       Dict             =	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 _lowercase	(     self		:						str							,						UpperCAmelCase__		:						Tuple							,						UpperCAmelCase__		:						Optional[int]							,						UpperCAmelCase__		:						str							,						UpperCAmelCase__		:						List[Any]							,						)					->       List[Any]:
   _a  :       Optional[int]             =	True
   _a  :       Union[str, Any]             =	TrOCRDecoder(config=UpperCAmelCase__							).to(UpperCAmelCase__							).eval()
   _a  :       List[str]             =	input_ids[:2]

   input_ids[input_ids == 0] += 1
   # first forward pass
   _a  :       List[Any]             =	model(UpperCAmelCase__							,						use_cache=UpperCAmelCase__							)
   _a  :       str             =	model(UpperCAmelCase__							)
   _a  :       Optional[Any]             =	model(UpperCAmelCase__							,						use_cache=UpperCAmelCase__							)

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

   _a  :       int             =	outputs["""past_key_values"""]

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

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

   _a  :       int             =	model(UpperCAmelCase__							)["""last_hidden_state"""]
   _a  :       Dict             =	model(UpperCAmelCase__							,						past_key_values=UpperCAmelCase__							)["""last_hidden_state"""]

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

   _a  :       Dict             =	{"""input_ids""": input_ids, """attention_mask""": attention_mask}
   return config, inputs_dict







@require_torch
class        UpperCamelCase			(	snake_case_		,     snake_case_		,     snake_case_		,     unittest.TestCase      ):
 UpperCamelCase					:       Any			=					(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
 UpperCamelCase					:       Dict			=					(TrOCRForCausalLM,) if is_torch_available() else ()
 UpperCamelCase					:       str			=					{'''text-generation''': TrOCRForCausalLM} if is_torch_available() else {}
 UpperCamelCase					:       List[str]			=					True
 UpperCamelCase					:       Tuple			=					False


 def _lowercase	(     self		:						Optional[int]							)					->       int:
   _a  :       List[Any]             =	TrOCRStandaloneDecoderModelTester(self							,						is_training=UpperCAmelCase__							)
   _a  :       Optional[int]             =	ConfigTester(self							,						config_class=UpperCAmelCase__							)


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


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


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


 def _lowercase	(     self		:						Tuple							)					->       str:
   self.config_tester.run_common_tests()


 def _lowercase	(     self		:						Dict							)					->       Union[str, Any]:
   _a  :       Any             =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_decoder_model_past(*UpperCAmelCase__							)


 def _lowercase	(     self		:						str							)					->       Tuple:
   return







 @unittest.skip("""The model doesn't support left padding"""							)  # and it's not used enough to be worth fixing :)
 def _lowercase	(     self		:						Dict							)					->       str:
   pass









"""simple docstring"""




from collections.abc import Iterable
from typing import Generic, TypeVar

_snake_case          =   TypeVar('_T')






class        UpperCamelCase			(	Generic[_T]      ):


 def __init__(     self		:						Optional[int]							,						UpperCAmelCase__		:						Iterable[_T] | None = None							)					->       None:
   _a  :       list[_T]             =	list(iterable or []							)
   _a  :       list[_T]             =	[]


 def __len__(     self		:						str							)					->       int:
   return len(self._stacka							) + len(self._stacka							)


 def __repr__(     self		:						List[str]							)					->       str:
   return f"""Queue({tuple(self._stacka[::-1] + self._stacka							)})"""


 def _lowercase	(     self		:						Union[str, Any]							,						UpperCAmelCase__		:						_T							)					->       None:
   self._stacka.append(UpperCAmelCase__							)







 def _lowercase	(     self		:						Optional[Any]							)					->       _T:
   _a  :       Any             =	self._stacka.pop
   _a  :       Union[str, Any]             =	self._stacka.append

   if not self._stacka:
     while self._stacka:
       stacka_append(stacka_pop()							)

   if not self._stacka:
     raise IndexError("""Queue is empty"""							)
   return self._stacka.pop()


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

 testmod()

