






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






    def __init__(					self      ,A      ,A=99      ,A=13      ,A=16      ,A=7      ,A=True      ,A=True      ,A=True      ,A=False      ,A=True      ,A=2      ,A=32      ,A=4      ,A=4      ,A=30      ,A=0      ,A=1      ,A=2      ,A=None      ,):
          UpperCAmelCase							     =			parent
          UpperCAmelCase							     =			batch_size
          UpperCAmelCase							     =			decoder_seq_length
          # For common tests
          UpperCAmelCase							     =			self.decoder_seq_length
          UpperCAmelCase							     =			is_training
          UpperCAmelCase							     =			use_attention_mask
          UpperCAmelCase							     =			use_labels

          UpperCAmelCase							     =			vocab_size
          UpperCAmelCase							     =			d_model
          UpperCAmelCase							     =			d_model
          UpperCAmelCase							     =			decoder_layers
          UpperCAmelCase							     =			decoder_layers
          UpperCAmelCase							     =			decoder_ffn_dim
          UpperCAmelCase							     =			decoder_attention_heads
          UpperCAmelCase							     =			decoder_attention_heads
          UpperCAmelCase							     =			eos_token_id
          UpperCAmelCase							     =			bos_token_id
          UpperCAmelCase							     =			pad_token_id
          UpperCAmelCase							     =			decoder_start_token_id
          UpperCAmelCase							     =			use_cache
          UpperCAmelCase							     =			max_position_embeddings

          UpperCAmelCase							     =			None
          UpperCAmelCase							     =			decoder_seq_length
          UpperCAmelCase							     =			2
          UpperCAmelCase							     =			1






    def 							_UpperCamelCase				(					self   ):
          UpperCAmelCase							     =			ids_tensor([self.batch_size, self.decoder_seq_length]      ,self.vocab_size   )

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

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

          UpperCAmelCase							     =			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      ,A      ,A      ,A      ,A      ,):
          UpperCAmelCase							     =			True
          UpperCAmelCase							     =			TrOCRDecoder(config=snake_case__   ).to(snake_case__   ).eval()
          UpperCAmelCase							     =			input_ids[:2]

          input_ids[input_ids == 0] += 1
          # first forward pass
          UpperCAmelCase							     =			model(snake_case__      ,use_cache=snake_case__   )
          UpperCAmelCase							     =			model(snake_case__   )
          UpperCAmelCase							     =			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							     =			outputs["past_key_values"]

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

          # append to next input_ids and
          UpperCAmelCase							     =			torch.cat([input_ids, next_tokens]      ,dim=-1   )

          UpperCAmelCase							     =			model(snake_case__   )["last_hidden_state"]
          UpperCAmelCase							     =			model(snake_case__      ,past_key_values=snake_case__   )["last_hidden_state"]

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

          UpperCAmelCase							     =			{"input_ids": input_ids, "attention_mask": attention_mask}
          return config, inputs_dict







@require_torch
class    lowerCamelCase__   (			snake_case       ,	snake_case       ,	snake_case       ,	unittest.TestCase					):
    SCREAMING_SNAKE_CASE						=     (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE						=     (TrOCRForCausalLM,) if is_torch_available() else ()
    SCREAMING_SNAKE_CASE						=     {"text-generation": TrOCRForCausalLM} if is_torch_available() else {}
    SCREAMING_SNAKE_CASE						=     True
    SCREAMING_SNAKE_CASE						=     False






    def 							_UpperCamelCase				(					self   ):
          UpperCAmelCase							     =			TrOCRStandaloneDecoderModelTester(self      ,is_training=snake_case__   )
          UpperCAmelCase							     =			ConfigTester(self      ,config_class=snake_case__   )






    def 							_UpperCamelCase				(					self   ):
          pass






    def 							_UpperCamelCase				(					self   ):
          pass






    def 							_UpperCamelCase				(					self   ):
          pass






    def 							_UpperCamelCase				(					self   ):
          self.config_tester.run_common_tests()






    def 							_UpperCamelCase				(					self   ):
          UpperCAmelCase							     =			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_decoder_model_past(*snake_case__   )






    def 							_UpperCamelCase				(					self   ):
          return






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





'''simple docstring'''





SCREAMING_SNAKE_CASE     =       {
    """meter""": """m""",
    """kilometer""": """km""",
    """megametre""": """Mm""",
    """gigametre""": """Gm""",
    """terametre""": """Tm""",
    """petametre""": """Pm""",
    """exametre""": """Em""",
    """zettametre""": """Zm""",
    """yottametre""": """Ym""",
}
# Exponent of the factor(meter)
SCREAMING_SNAKE_CASE     =       {
    """m""": 0,
    """km""": 3,
    """Mm""": 6,
    """Gm""": 9,
    """Tm""": 1_2,
    """Pm""": 1_5,
    """Em""": 1_8,
    """Zm""": 2_1,
    """Ym""": 2_4,
}







def snake_case_     (					lowercase__   ,       lowercase__   ,       lowercase__		):
  UpperCAmelCase__      :					str				       =							from_type.lower().strip("s"		)
  UpperCAmelCase__      :					Any				       =							to_type.lower().strip("s"		)

  UpperCAmelCase__      :					Union[str, Any]				       =							UNIT_SYMBOL.get(lowercase__   ,       lowercase__		)
  UpperCAmelCase__      :					Any				       =							UNIT_SYMBOL.get(lowercase__   ,       lowercase__		)

  if from_sanitized not in METRIC_CONVERSION:
    UpperCAmelCase__      :					str				       =							(
        F"""Invalid 'from_type' value: {from_type!r}.\n"""
        F"""Conversion abbreviations are: {", ".join(lowercase__		)}"""
    )
    raise ValueError(lowercase__		)
  if to_sanitized not in METRIC_CONVERSION:
    UpperCAmelCase__      :					List[str]				       =							(
        F"""Invalid 'to_type' value: {to_type!r}.\n"""
        F"""Conversion abbreviations are: {", ".join(lowercase__		)}"""
    )
    raise ValueError(lowercase__		)
  UpperCAmelCase__      :					Optional[int]				       =							METRIC_CONVERSION[from_sanitized]
  UpperCAmelCase__      :					str				       =							METRIC_CONVERSION[to_sanitized]
  UpperCAmelCase__      :					Tuple				       =							1

  if from_exponent > to_exponent:
    UpperCAmelCase__      :					Tuple				       =							from_exponent - to_exponent
  else:
    UpperCAmelCase__      :					Optional[int]				       =							-(to_exponent - from_exponent)

  return value * pow(1_0   ,       lowercase__		)


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

      testmod()



