
'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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 DonutImageProcessor

class 			UpperCAmelCase__    (							unittest.TestCase			):



    def __init__(						self   :							Optional[int],__A   :							Any,__A   :							Tuple=7,__A   :							List[Any]=3,__A   :							str=1_8,__A   :							Tuple=3_0,__A   :							Dict=4_0_0,__A   :							int=True,__A   :							List[Any]=None,__A   :							Any=True,__A   :							int=False,__A   :							str=True,__A   :							int=True,__A   :							Any=[0.5, 0.5, 0.5],__A   :							Dict=[0.5, 0.5, 0.5],):
          _lowerCamelCase					: str		    = parent
          _lowerCamelCase					: Dict		    = batch_size
          _lowerCamelCase					: List[Any]		    = num_channels
          _lowerCamelCase					: Dict		    = image_size
          _lowerCamelCase					: Tuple		    = min_resolution
          _lowerCamelCase					: List[str]		    = max_resolution
          _lowerCamelCase					: str		    = do_resize
          _lowerCamelCase					: int		    = size if size is not None else {"height": 1_8, "width": 2_0}
          _lowerCamelCase					: Union[str, Any]		    = do_thumbnail
          _lowerCamelCase					: Optional[int]		    = do_align_axis
          _lowerCamelCase					: Any		    = do_pad
          _lowerCamelCase					: Tuple		    = do_normalize
          _lowerCamelCase					: str		    = image_mean
          _lowerCamelCase					: int		    = image_std



    def 	lowerCamelCase_	(						self   :							List[Any]  ):
          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_thumbnail": self.do_thumbnail,
              "do_align_long_axis": self.do_align_axis,
              "do_pad": self.do_pad,
              "do_normalize": self.do_normalize,
              "image_mean": self.image_mean,
              "image_std": self.image_std,
          }


@require_torch
@require_vision
class 			UpperCAmelCase__    (							A    ,						unittest.TestCase			):
    lowerCAmelCase_					     =		DonutImageProcessor if is_vision_available() else None



    def 	lowerCamelCase_	(						self   :							Dict  ):
          _lowerCamelCase					: int		    = DonutImageProcessingTester(self  )



    @property
    def 	lowerCamelCase_	(						self   :							Any  ):
          return self.image_processor_tester.prepare_image_processor_dict()



    def 	lowerCamelCase_	(						self   :							Tuple  ):
          _lowerCamelCase					: Any		    = self.image_processing_class(**self.image_processor_dict  )
          self.assertTrue(hasattr(__A,"do_resize"  )  )
          self.assertTrue(hasattr(__A,"size"  )  )
          self.assertTrue(hasattr(__A,"do_thumbnail"  )  )
          self.assertTrue(hasattr(__A,"do_align_long_axis"  )  )
          self.assertTrue(hasattr(__A,"do_pad"  )  )
          self.assertTrue(hasattr(__A,"do_normalize"  )  )
          self.assertTrue(hasattr(__A,"image_mean"  )  )
          self.assertTrue(hasattr(__A,"image_std"  )  )



    def 	lowerCamelCase_	(						self   :							Tuple  ):
          _lowerCamelCase					: List[str]		    = self.image_processing_class.from_dict(self.image_processor_dict  )
          self.assertEqual(image_processor.size,{"height": 1_8, "width": 2_0}  )

          _lowerCamelCase					: Optional[Any]		    = self.image_processing_class.from_dict(self.image_processor_dict,size=4_2  )
          self.assertEqual(image_processor.size,{"height": 4_2, "width": 4_2}  )

          # Previous config had dimensions in (width, height) order
          _lowerCamelCase					: Any		    = self.image_processing_class.from_dict(self.image_processor_dict,size=(4_2, 8_4)  )
          self.assertEqual(image_processor.size,{"height": 8_4, "width": 4_2}  )



    def 	lowerCamelCase_	(						self   :							List[Any]  ):
          pass



    @is_flaky()
    def 	lowerCamelCase_	(						self   :							Dict  ):
          # Initialize image_processing
          _lowerCamelCase					: List[str]		    = self.image_processing_class(**self.image_processor_dict  )
          # create random PIL images
          _lowerCamelCase					: Optional[Any]		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,Image.Image  )

          # Test not batched input
          _lowerCamelCase					: 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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)

          # Test batched
          _lowerCamelCase					: int		    = image_processing(__A,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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)



    @is_flaky()
    def 	lowerCamelCase_	(						self   :							List[str]  ):
          # Initialize image_processing
          _lowerCamelCase					: str		    = self.image_processing_class(**self.image_processor_dict  )
          # create random numpy tensors
          _lowerCamelCase					: List[str]		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,numpify=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,np.ndarray  )

          # Test not batched input
          _lowerCamelCase					: List[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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)

          # Test batched
          _lowerCamelCase					: List[Any]		    = image_processing(__A,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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)



    @is_flaky()
    def 	lowerCamelCase_	(						self   :							Optional[Any]  ):
          # Initialize image_processing
          _lowerCamelCase					: Optional[int]		    = self.image_processing_class(**self.image_processor_dict  )
          # create random PyTorch tensors
          _lowerCamelCase					: List[str]		    = prepare_image_inputs(self.image_processor_tester,equal_resolution=__A,torchify=__A  )
          for image in image_inputs:
                self.assertIsInstance(__A,torch.Tensor  )

          # Test not batched input
          _lowerCamelCase					: Tuple		    = 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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)

          # Test batched
          _lowerCamelCase					: int		    = image_processing(__A,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.size["height"],
                  self.image_processor_tester.size["width"],
              ),)






'''simple docstring'''

from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


a   	=    logging.get_logger(__name__)

a   	=    {
    "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
    "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
    "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
    "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
    "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
    "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
}







class __a			( _snake_case      ):
   __UpperCamelCase :			List[str]						   =						'bloom'
   __UpperCamelCase :			Optional[Any]						   =						['past_key_values']
   __UpperCamelCase :			Optional[int]						   =						{
       'num_hidden_layers': 'n_layer',
       'num_attention_heads': 'n_head',
   }





   def __init__(       self					:      Union[str, Any]					,lowerCamelCase					:      str=25_0880					,lowerCamelCase					:      List[Any]=64					,lowerCamelCase					:      Optional[Any]=2					,lowerCamelCase					:      Tuple=8					,lowerCamelCase					:      Union[str, Any]=1E-5					,lowerCamelCase					:      Optional[Any]=0.02					,lowerCamelCase					:      str=True					,lowerCamelCase					:      List[Any]=1					,lowerCamelCase					:      Union[str, Any]=2					,lowerCamelCase					:      Optional[int]=False					,lowerCamelCase					:      Optional[int]=0.0					,lowerCamelCase					:      List[Any]=0.0					,lowerCamelCase					:      Optional[Any]=1					,lowerCamelCase					:      Tuple=False					,**lowerCamelCase					:      str					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							vocab_size
      # Backward compatibility with n_embed kwarg
      __SCREAMING_SNAKE_CASE   				=							kwargs.pop("""n_embed"""					,lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							hidden_size if n_embed is None else n_embed
      __SCREAMING_SNAKE_CASE   				=							n_layer
      __SCREAMING_SNAKE_CASE   				=							n_head
      __SCREAMING_SNAKE_CASE   				=							layer_norm_epsilon
      __SCREAMING_SNAKE_CASE   				=							initializer_range
      __SCREAMING_SNAKE_CASE   				=							use_cache
      __SCREAMING_SNAKE_CASE   				=							pretraining_tp
      __SCREAMING_SNAKE_CASE   				=							apply_residual_connection_post_layernorm
      __SCREAMING_SNAKE_CASE   				=							hidden_dropout
      __SCREAMING_SNAKE_CASE   				=							attention_dropout

      __SCREAMING_SNAKE_CASE   				=							bos_token_id
      __SCREAMING_SNAKE_CASE   				=							eos_token_id
      __SCREAMING_SNAKE_CASE   				=							slow_but_exact

      super().__init__(bos_token_id=lowerCamelCase					,eos_token_id=lowerCamelCase					,**lowerCamelCase     )







class __a			( _snake_case      ):
   __UpperCamelCase :			int						   =						version.parse('1.12'      )





   def __init__(       self					:      Optional[int]					,lowerCamelCase					:      PretrainedConfig					,lowerCamelCase					:      str = "default"					,lowerCamelCase					:      List[PatchingSpec] = None					,lowerCamelCase					:      bool = False					,):

      '''simple docstring'''

      super().__init__(lowerCamelCase					,task=lowerCamelCase					,patching_specs=lowerCamelCase					,use_past=lowerCamelCase     )
      if not getattr(self._config					,"""pad_token_id"""					,lowerCamelCase     ):
         # TODO: how to do that better?
         __SCREAMING_SNAKE_CASE   				=							0





   @property
   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}     )
      if self.use_past:
         # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
         self.fill_with_past_key_values_(lowerCamelCase					,direction="""inputs"""					,inverted_values_shape=lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """past_sequence + sequence"""}
      else:
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """sequence"""}

      return common_inputs





   @property
   def   UpperCAmelCase__  (       self					:      Tuple     ):

      '''simple docstring'''

      return self._config.n_layer





   @property
   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      return self._config.n_head





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 1E-3





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      "PreTrainedTokenizer"					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      bool = False					,lowerCamelCase					:      Optional["TensorType"] = None					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							super(lowerCamelCase					,self     ).generate_dummy_inputs(
          lowerCamelCase					,batch_size=lowerCamelCase					,seq_length=lowerCamelCase					,is_pair=lowerCamelCase					,framework=lowerCamelCase     )

      # We need to order the input in the way they appears in the forward()
      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}     )

      # Need to add the past_keys
      if self.use_past:
         if not is_torch_available():
            raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""     )
         else:
            import torch

            __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							common_inputs["""input_ids"""].shape
            # Not using the same length for past_key_values
            __SCREAMING_SNAKE_CASE   				=							seqlen + 2
            __SCREAMING_SNAKE_CASE   				=							self._config.hidden_size // self.num_attention_heads
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                head_dim,
                past_key_values_length,
            )
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                past_key_values_length,
                head_dim,
            )
            __SCREAMING_SNAKE_CASE   				=							[
                (torch.zeros(lowerCamelCase     ), torch.zeros(lowerCamelCase     )) for _ in range(self.num_layers     )
            ]

      __SCREAMING_SNAKE_CASE   				=							common_inputs["""attention_mask"""]
      if self.use_past:
         __SCREAMING_SNAKE_CASE   				=							ordered_inputs["""attention_mask"""].dtype
         __SCREAMING_SNAKE_CASE   				=							torch.cat(
             [ordered_inputs["""attention_mask"""], torch.ones(lowerCamelCase					,lowerCamelCase					,dtype=lowerCamelCase     )]					,dim=1     )

      return ordered_inputs





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 13





