

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 LevitImageProcessor


class       SCREAMING_SNAKE_CASE__					(unittest.TestCase     ):





    def __init__(      self						,   a						,   a=7						,   a=3						,   a=18						,   a=30						,   a=400						,   a=True						,   a=None						,   a=True						,   a=None						,   a=True						,   a=[0.5, 0.5, 0.5]						,   a=[0.5, 0.5, 0.5]						,   ):
         lowercase__    :   Union[str, Any]      =       size if size is not None else {'shortest_edge': 18}
         lowercase__    :   Any      =       crop_size if crop_size is not None else {'height': 18, 'width': 18}
         lowercase__    :   List[str]      =       parent
         lowercase__    :   Union[str, Any]      =       batch_size
         lowercase__    :   List[str]      =       num_channels
         lowercase__    :   Any      =       image_size
         lowercase__    :   Any      =       min_resolution
         lowercase__    :   int      =       max_resolution
         lowercase__    :   Dict      =       do_resize
         lowercase__    :   str      =       size
         lowercase__    :   List[Any]      =       do_center_crop
         lowercase__    :   Optional[int]      =       crop_size
         lowercase__    :   Dict      =       do_normalize
         lowercase__    :   Union[str, Any]      =       image_mean
         lowercase__    :   int      =       image_std





    def       snake_case_				(      self):
         return {
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_normalize": self.do_normalize,
             "do_resize": self.do_resize,
             "do_center_crop": self.do_center_crop,
             "size": self.size,
             "crop_size": self.crop_size,
         }



@require_torch
@require_vision
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       Optional[Any]														=     LevitImageProcessor if is_vision_available() else None





    def       snake_case_				(      self):
         lowercase__    :   Optional[int]      =       LevitImageProcessingTester(self)





    @property
    def       snake_case_				(      self):
         return self.image_processor_tester.prepare_image_processor_dict()





    def       snake_case_				(      self):
         lowercase__    :   List[Any]      =       self.image_processing_class(**self.image_processor_dict)
         self.assertTrue(hasattr(a						,   'image_mean'))
         self.assertTrue(hasattr(a						,   'image_std'))
         self.assertTrue(hasattr(a						,   'do_normalize'))
         self.assertTrue(hasattr(a						,   'do_resize'))
         self.assertTrue(hasattr(a						,   'do_center_crop'))
         self.assertTrue(hasattr(a						,   'size'))





    def       snake_case_				(      self):
         lowercase__    :   Tuple      =       self.image_processing_class.from_dict(self.image_processor_dict)
         self.assertEqual(image_processor.size						,   {'shortest_edge': 18})
         self.assertEqual(image_processor.crop_size						,   {'height': 18, 'width': 18})

         lowercase__    :   Optional[int]      =       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       snake_case_				(      self):
         pass





    def       snake_case_				(      self):
         # Initialize image_processing
         lowercase__    :   Optional[Any]      =       self.image_processing_class(**self.image_processor_dict)
         # create random PIL images
         lowercase__    :   List[str]      =       prepare_image_inputs(self.image_processor_tester						,   equal_resolution=a)
         for image in image_inputs:
              self.assertIsInstance(a						,   Image.Image)

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





    def       snake_case_				(      self):
         # Initialize image_processing
         lowercase__    :   Dict      =       self.image_processing_class(**self.image_processor_dict)
         # create random numpy tensors
         lowercase__    :   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
         lowercase__    :   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
         lowercase__    :   Union[str, 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.crop_size['height'],
                 self.image_processor_tester.crop_size['width'],
             )						,   )





    def       snake_case_				(      self):
         # Initialize image_processing
         lowercase__    :   List[Any]      =       self.image_processing_class(**self.image_processor_dict)
         # create random PyTorch tensors
         lowercase__    :   Any      =       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
         lowercase__    :   str      =       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
         lowercase__    :   Optional[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.crop_size['height'],
                 self.image_processor_tester.crop_size['width'],
             )						,   )




from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_			  = logging.get_logger(__name__)

snake_case_			  = {
    '''google/switch-base-8''': '''https://huggingface.co/google/switch-base-8/blob/main/config.json''',
}


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       int														=     """switch_transformers"""
    __lowerCamelCase						:       Optional[Any]														=     ["""past_key_values"""]
    __lowerCamelCase						:       Any														=     {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}





    def __init__(      self						,   a=3_2128						,   a=768						,   a=64						,   a=2048						,   a=64						,   a=12						,   a=3						,   a=12						,   a=3						,   a=12						,   a=8						,   a=False						,   a=0.01						,   a="float32"						,   a=False						,   a=32						,   a=128						,   a=0.1						,   a=1e-6						,   a=0.001						,   a=0.001						,   a=1.0						,   a="relu"						,   a=True						,   a=False						,   a=True						,   a=0						,   a=1						,   **a						,   ):
         lowercase__    :   Optional[int]      =       vocab_size
         lowercase__    :   List[Any]      =       d_model
         lowercase__    :   List[Any]      =       d_kv
         lowercase__    :   Any      =       d_ff

         lowercase__    :   Optional[int]      =       num_sparse_encoder_layers

         lowercase__    :   Tuple      =       num_layers
         lowercase__    :   Optional[Any]      =       (
             num_decoder_layers if num_decoder_layers is not None else self.num_layers
         )  # default = symmetry
         lowercase__    :   str      =       num_sparse_decoder_layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_encoder_layers > 0:
              lowercase__    :   Optional[Any]      =       self.num_layers // self.num_sparse_encoder_layers
         else:
              lowercase__    :   Optional[int]      =       self.num_layers  # HACK: this will create 0 sparse layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_decoder_layers > 0:
              lowercase__    :   Union[str, Any]      =       self.num_decoder_layers // self.num_sparse_decoder_layers
         else:
              lowercase__    :   int      =       self.num_decoder_layers  # HACK: this will create 0 sparse layers

         lowercase__    :   List[Any]      =       num_heads
         lowercase__    :   Union[str, Any]      =       num_experts
         lowercase__    :   str      =       expert_capacity
         lowercase__    :   List[Any]      =       router_bias
         lowercase__    :   Optional[int]      =       router_jitter_noise
         if router_dtype not in ["float32", "float16", "bfloat16"]:
              raise ValueError(f"""`router_dtype` must be one of 'float32', 'float16' or 'bfloat16', got {router_dtype}""")
         lowercase__    :   str      =       router_dtype

         lowercase__    :   Optional[int]      =       router_ignore_padding_tokens
         lowercase__    :   int      =       relative_attention_num_buckets
         lowercase__    :   Optional[Any]      =       relative_attention_max_distance

         lowercase__    :   List[str]      =       dropout_rate
         lowercase__    :   str      =       layer_norm_epsilon
         lowercase__    :   int      =       initializer_factor
         lowercase__    :   int      =       feed_forward_proj
         lowercase__    :   Dict      =       use_cache
         lowercase__    :   int      =       add_router_probs

         lowercase__    :   int      =       router_z_loss_coef
         lowercase__    :   List[Any]      =       router_aux_loss_coef

         lowercase__    :   int      =       self.feed_forward_proj.split('-')
         lowercase__    :   Optional[int]      =       act_info[-1]
         lowercase__    :   Dict      =       act_info[0] == 'gated'

         if len(a) > 1 and act_info[0] != "gated" or len(a) > 2:
              raise ValueError(
                  f"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."""
                  'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
                  '\'gated-gelu\' or \'relu\'')

         # for backwards compatibility
         if feed_forward_proj == "gated-gelu":
              lowercase__    :   Optional[int]      =       'gelu_new'

         super().__init__(
             pad_token_id=a						,   eos_token_id=a						,   is_encoder_decoder=a						,   **a						,   )

