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



   '''simple docstring'''




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

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

   UpperCAmelCase__      :					Tuple				       =							None
   UpperCAmelCase__      :					Optional[int]				       =							decoder_seq_length
   UpperCAmelCase__      :					Optional[Any]				       =							2
   UpperCAmelCase__      :					List[Any]				       =							1







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




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

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

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

   UpperCAmelCase__      :					Union[str, Any]				       =							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 							UpperCamelCase  (					self		:  Union[str, Any]			,				snake_case__		:  Union[str, Any]			,				snake_case__		:  Tuple			,				snake_case__		:  Tuple			,				snake_case__		:  Optional[int]			,				):



   '''simple docstring'''




   UpperCAmelCase__      :					Union[str, Any]				       =							True
   UpperCAmelCase__      :					Any				       =							TrOCRDecoder(config=snake_case__ ).to(snake_case__ ).eval()
   UpperCAmelCase__      :					Any				       =							input_ids[:2]

   input_ids[input_ids == 0] += 1
   # first forward pass
   UpperCAmelCase__      :					Any				       =							model(snake_case__			,				use_cache=snake_case__ )
   UpperCAmelCase__      :					Optional[int]				       =							model(snake_case__ )
   UpperCAmelCase__      :					Dict				       =							model(snake_case__			,				use_cache=snake_case__ )

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

   UpperCAmelCase__      :					str				       =							outputs["past_key_values"]

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

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

   UpperCAmelCase__      :					Optional[int]				       =							model(snake_case__ )["last_hidden_state"]
   UpperCAmelCase__      :					List[str]				       =							model(snake_case__			,				past_key_values=snake_case__ )["last_hidden_state"]

   # select random slice
   UpperCAmelCase__      :					int				       =							ids_tensor((1,)			,				output_from_past.shape[-1] ).item()
   UpperCAmelCase__      :					Tuple				       =							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(snake_case__			,				snake_case__			,				atol=1e-3 )







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							self.prepare_config_and_inputs()
   UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__       ,			UpperCAmelCase__      :					Optional[int]				       =							config_and_inputs

   UpperCAmelCase__      :					int				       =							{"input_ids": input_ids, "attention_mask": attention_mask}
   return config, inputs_dict






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

 '''simple docstring'''
 lowercase_					:    str				=							(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
 lowercase_					:    Union[str, Any]				=							(TrOCRForCausalLM,) if is_torch_available() else ()
 lowercase_					:    Optional[Any]				=							{"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
 lowercase_					:    List[str]				=							True
 lowercase_					:    Optional[int]				=							False







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							TrOCRStandaloneDecoderModelTester(self			,				is_training=snake_case__ )
   UpperCAmelCase__      :					Dict				       =							ConfigTester(self			,				config_class=snake_case__ )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   pass







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   pass







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   pass







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   self.config_tester.run_common_tests()







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_decoder_model_past(*snake_case__ )







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   return







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



   '''simple docstring'''




   pass





'''simple docstring'''





import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate







def snake_case_     (					lowercase__		):
  return x + 2






class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  Optional[int] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"x = 3"
   UpperCAmelCase__      :					List[str]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )

   UpperCAmelCase__      :					Any				       =							"x = y"
   UpperCAmelCase__      :					List[str]				       =							{"y": 5}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 5, "y": 5} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"y = add_two(x)"
   UpperCAmelCase__      :					Tuple				       =							{"x": 3}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )

   # Won't work without the tool
   with CaptureStdout() as out:
     UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result is None
   assert "tried to execute add_two" in out.out







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							"x = 3"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Tuple				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3} )







 def 							UpperCamelCase  (					self		:  Dict ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"test_dict = {'x': x, 'y': add_two(x)}"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					int				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







 def 							UpperCamelCase  (					self		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							"x = 3\ny = 5"
   UpperCAmelCase__      :					Dict				       =							{}
   UpperCAmelCase__      :					Union[str, Any]				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 5} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Dict				       =							"text = f'This is x: {x}.'"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == "This is x: 3."
   self.assertDictEqual(snake_case__			,				{"x": 3, "text": "This is x: 3."} )







 def 							UpperCamelCase  (					self		:  List[Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							"if x <= 3:\n    y = 2\nelse:\n    y = 5"
   UpperCAmelCase__      :					Dict				       =							{"x": 3}
   UpperCAmelCase__      :					Dict				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 2} )

   UpperCAmelCase__      :					Optional[Any]				       =							{"x": 8}
   UpperCAmelCase__      :					str				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   # evaluate returns the value of the last assignment.
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 8, "y": 5} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]"
   UpperCAmelCase__      :					Any				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   self.assertListEqual(snake_case__			,				[3, 5] )
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							"y = x"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{}			,				state=snake_case__ )
   assert result == 3
   self.assertDictEqual(snake_case__			,				{"x": 3, "y": 3} )







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							"test_list = [x, add_two(x)]\ntest_list[1]"
   UpperCAmelCase__      :					List[Any]				       =							{"x": 3}
   UpperCAmelCase__      :					List[Any]				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_list": [3, 5]} )

   UpperCAmelCase__      :					Union[str, Any]				       =							"test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
   UpperCAmelCase__      :					str				       =							{"x": 3}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"add_two": add_two}			,				state=snake_case__ )
   assert result == 5
   self.assertDictEqual(snake_case__			,				{"x": 3, "test_dict": {"x": 3, "y": 5}} )







 def 							UpperCamelCase  (					self		:  Union[str, Any] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							"x = 0\nfor i in range(3):\n    x = i"
   UpperCAmelCase__      :					List[Any]				       =							{}
   UpperCAmelCase__      :					Any				       =							evaluate(snake_case__			,				{"range": range}			,				state=snake_case__ )
   assert result == 2
   self.assertDictEqual(snake_case__			,				{"x": 2, "i": 2} )



