'''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   ,    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'''







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

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

    __UpperCAmelCase:					str		= None
    __UpperCAmelCase:					int		= decoder_seq_length
    __UpperCAmelCase:					Union[str, Any]		= 2
    __UpperCAmelCase:					Optional[Any]		= 1







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= ids_tensor([self.batch_size, self.decoder_seq_length]   ,    self.vocab_size					)

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

    __UpperCAmelCase:					Optional[int]		= None
    if self.use_labels:
      __UpperCAmelCase:					Union[str, 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    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_   ,    snake_case_   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					Tuple		= True
    __UpperCAmelCase:					Dict		= TrOCRDecoder(config=lowerCAmelCase_					).to(lowerCAmelCase_					).eval()
    __UpperCAmelCase:					Dict		= input_ids[:2]

    input_ids[input_ids == 0] += 1
    # first forward pass
    __UpperCAmelCase:					Optional[Any]		= model(lowerCAmelCase_   ,    use_cache=lowerCAmelCase_					)
    __UpperCAmelCase:					Optional[int]		= model(lowerCAmelCase_					)
    __UpperCAmelCase:					str		= model(lowerCAmelCase_   ,    use_cache=lowerCAmelCase_					)

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

    __UpperCAmelCase:					Optional[Any]		= outputs["""past_key_values"""]

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

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

    __UpperCAmelCase:					Any		= model(lowerCAmelCase_					)["""last_hidden_state"""]
    __UpperCAmelCase:					Any		= model(lowerCAmelCase_   ,    past_key_values=lowerCAmelCase_					)["""last_hidden_state"""]

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

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







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Tuple		= self.prepare_config_and_inputs()
    __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase:					Tuple		= config_and_inputs

    __UpperCAmelCase:					Union[str, Any]		= {"""input_ids""": input_ids, """attention_mask""": attention_mask}
    return config, inputs_dict




@require_torch
class    a (       __UpperCAmelCase						,  __UpperCAmelCase						,  __UpperCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					(TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
  __lowerCAmelCase				      =					(TrOCRForCausalLM,) if is_torch_available() else ()
  __lowerCAmelCase				      =					{"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {}
  __lowerCAmelCase				      =					True
  __lowerCAmelCase				      =					False







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Dict		= TrOCRStandaloneDecoderModelTester(self   ,    is_training=lowerCAmelCase_					)
    __UpperCAmelCase:					Optional[Any]		= ConfigTester(self   ,    config_class=lowerCAmelCase_					)







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







    __UpperCAmelCase:					Any		= self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_decoder_model_past(*lowerCAmelCase_					)







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






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class    a (       unittest.TestCase				):



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=7   ,    snake_case_=3   ,    snake_case_=30   ,    snake_case_=400   ,    snake_case_=True   ,    snake_case_=None   ,    snake_case_=0.9   ,    snake_case_=None   ,    snake_case_=True   ,    snake_case_=[0.5, 0.5, 0.5]   ,    snake_case_=[0.5, 0.5, 0.5]   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= size if size is not None else {"""shortest_edge""": 30}
    __UpperCAmelCase:					str		= crop_size if crop_size is not None else {"""height""": 30, """width""": 30}
    __UpperCAmelCase:					Dict		= parent
    __UpperCAmelCase:					Union[str, Any]		= batch_size
    __UpperCAmelCase:					List[Any]		= num_channels
    __UpperCAmelCase:					List[str]		= min_resolution
    __UpperCAmelCase:					List[str]		= max_resolution
    __UpperCAmelCase:					Tuple		= do_resize_and_center_crop
    __UpperCAmelCase:					Union[str, Any]		= size
    __UpperCAmelCase:					str		= crop_pct
    __UpperCAmelCase:					List[Any]		= crop_size
    __UpperCAmelCase:					str		= do_normalize
    __UpperCAmelCase:					Union[str, Any]		= image_mean
    __UpperCAmelCase:					List[str]		= image_std







  def    lowercase_  (							self					):

    '''simple docstring'''







    return {
        "size": self.size,
        "do_resize_and_center_crop": self.do_resize_and_center_crop,
        "crop_pct": self.crop_pct,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
    }




@require_torch
@require_vision
class    a (       __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					PoolFormerImageProcessor if is_vision_available() else None







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= PoolFormerImageProcessingTester(self					)







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return self.image_processor_tester.prepare_image_processor_dict()







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    self.assertTrue(hasattr(snake_case_   ,    """do_resize_and_center_crop"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """size"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """crop_pct"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """do_normalize"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_mean"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_std"""					)					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processing_class.from_dict(self.image_processor_dict					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 30}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 30, """width""": 30}					)

    __UpperCAmelCase:					Dict		= self.image_processing_class.from_dict(self.image_processor_dict   ,    size=42   ,    crop_size=84					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 42}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 84, """width""": 84}					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PIL images
    __UpperCAmelCase:					Optional[Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    Image.Image					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values

    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Any		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    # create random numpy tensors
    __UpperCAmelCase:					Union[str, Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    numpify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    np.ndarray					)

    # Test not batched input
    __UpperCAmelCase:					Union[str, Any]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					str		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PyTorch tensors
    __UpperCAmelCase:					Dict		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    torchify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    torch.Tensor					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Optional[int]		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )