

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TFDeiTForImageClassification,
       TFDeiTForImageClassificationWithTeacher,
       TFDeiTForMaskedImageModeling,
       TFDeiTModel,
   )
   from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import DeiTImageProcessor



class        a					:





     def __init__(    self					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=13    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=30    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]=2    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=3    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=True    ,	SCREAMING_SNAKE_CASE_					:				Any=True    ,	SCREAMING_SNAKE_CASE_					:				Dict=32    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=2    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=4    ,	SCREAMING_SNAKE_CASE_					:				List[str]=37    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]="gelu"    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=0.1    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]=0.1    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]=10    ,	SCREAMING_SNAKE_CASE_					:				int=0.02    ,	SCREAMING_SNAKE_CASE_					:				List[str]=3    ,	SCREAMING_SNAKE_CASE_					:				Tuple=None    ,	SCREAMING_SNAKE_CASE_					:				Any=2    ,	):
        __lowerCamelCase:				int     =	parent
        __lowerCamelCase:				List[Any]     =	batch_size
        __lowerCamelCase:				Dict     =	image_size
        __lowerCamelCase:				Tuple     =	patch_size
        __lowerCamelCase:				List[str]     =	num_channels
        __lowerCamelCase:				List[str]     =	is_training
        __lowerCamelCase:				Dict     =	use_labels
        __lowerCamelCase:				List[str]     =	hidden_size
        __lowerCamelCase:				Tuple     =	num_hidden_layers
        __lowerCamelCase:				List[Any]     =	num_attention_heads
        __lowerCamelCase:				Union[str, Any]     =	intermediate_size
        __lowerCamelCase:				Union[str, Any]     =	hidden_act
        __lowerCamelCase:				List[str]     =	hidden_dropout_prob
        __lowerCamelCase:				Optional[Any]     =	attention_probs_dropout_prob
        __lowerCamelCase:				Optional[int]     =	type_sequence_label_size
        __lowerCamelCase:				Optional[Any]     =	initializer_range
        __lowerCamelCase:				Any     =	scope
        __lowerCamelCase:				Union[str, Any]     =	encoder_stride

        # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
        __lowerCamelCase:				Union[str, Any]     =	(image_size // patch_size) ** 2
        __lowerCamelCase:				Tuple     =	num_patches + 2





     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        __lowerCamelCase:				Tuple     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

        __lowerCamelCase:				Tuple     =	None
        if self.use_labels:
           __lowerCamelCase:				Tuple     =	ids_tensor([self.batch_size]    ,	self.type_sequence_label_size							)

        __lowerCamelCase:				str     =	self.get_config()

        return config, pixel_values, labels





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        return DeiTConfig(
            image_size=self.image_size    ,	patch_size=self.patch_size    ,	num_channels=self.num_channels    ,	hidden_size=self.hidden_size    ,	num_hidden_layers=self.num_hidden_layers    ,	num_attention_heads=self.num_attention_heads    ,	intermediate_size=self.intermediate_size    ,	hidden_act=self.hidden_act    ,	hidden_dropout_prob=self.hidden_dropout_prob    ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,	is_decoder=_A    ,	initializer_range=self.initializer_range    ,	encoder_stride=self.encoder_stride    ,	)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Tuple    ,	SCREAMING_SNAKE_CASE_					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				Dict							):
        __lowerCamelCase:				Optional[int]     =	TFDeiTModel(config=_A							)
        __lowerCamelCase:				Optional[Any]     =	model(_A							)
        self.parent.assertEqual(result.last_hidden_state.shape    ,	(self.batch_size, self.seq_length, self.hidden_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				str    ,	SCREAMING_SNAKE_CASE_					:				int    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				int							):
        __lowerCamelCase:				Union[str, Any]     =	TFDeiTForMaskedImageModeling(config=_A							)
        __lowerCamelCase:				Optional[Any]     =	model(_A							)
        self.parent.assertEqual(
            result.reconstruction.shape    ,	(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

        # test greyscale images
        __lowerCamelCase:				str     =	1
        __lowerCamelCase:				Optional[Any]     =	TFDeiTForMaskedImageModeling(_A							)

        __lowerCamelCase:				Tuple     =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
        __lowerCamelCase:				int     =	model(_A							)
        self.parent.assertEqual(result.reconstruction.shape    ,	(self.batch_size, 1, self.image_size, self.image_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Tuple							):
        __lowerCamelCase:				List[Any]     =	self.type_sequence_label_size
        __lowerCamelCase:				int     =	TFDeiTForImageClassification(_A							)
        __lowerCamelCase:				List[str]     =	model(_A    ,	labels=_A							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.type_sequence_label_size)							)

        # test greyscale images
        __lowerCamelCase:				Optional[Any]     =	1
        __lowerCamelCase:				List[Any]     =	TFDeiTForImageClassification(_A							)

        __lowerCamelCase:				Dict     =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
        __lowerCamelCase:				Optional[Any]     =	model(_A    ,	labels=_A							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.type_sequence_label_size)							)







     def  SCREAMING_SNAKE_CASE__       (    self					:				str							):
        __lowerCamelCase:				Dict     =	self.prepare_config_and_inputs()
        __lowerCamelCase   ,     __lowerCamelCase   ,     __lowerCamelCase:				Tuple     =	config_and_inputs
        __lowerCamelCase:				Tuple     =	{"""pixel_values""": pixel_values}
        return config, inputs_dict



@require_tf
class        a					(			__lowercase     ,__lowercase     ,unittest.TestCase   ):
     UpperCAmelCase__ :  Tuple						      =	(
         (
             TFDeiTModel,
             TFDeiTForImageClassification,
             TFDeiTForImageClassificationWithTeacher,
             TFDeiTForMaskedImageModeling,
         )
         if is_tf_available()
         else ()
     )
     UpperCAmelCase__ :  Dict						      =	(
         {
             "feature-extraction": TFDeiTModel,
             "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
         }
         if is_tf_available()
         else {}
     )

     UpperCAmelCase__ :  List[Any]						      =	False
     UpperCAmelCase__ :  int						      =	False
     UpperCAmelCase__ :  Tuple						      =	False
     UpperCAmelCase__ :  int						      =	False





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        __lowerCamelCase:				Any     =	TFDeiTModelTester(self							)
        __lowerCamelCase:				List[str]     =	ConfigTester(self    ,	config_class=_A    ,	has_text_modality=_A    ,	hidden_size=37							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        self.config_tester.run_common_tests()





     @unittest.skip(reason="""DeiT does not use inputs_embeds"""							)
     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        pass





     def  SCREAMING_SNAKE_CASE__       (    self					:				Tuple							):
        __lowerCamelCase   ,     __lowerCamelCase:				Optional[Any]     =	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           __lowerCamelCase:				List[str]     =	model_class(_A							)
           self.assertIsInstance(model.get_input_embeddings()    ,	(tf.keras.layers.Layer)							)
           __lowerCamelCase:				Optional[Any]     =	model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(_A    ,	tf.keras.layers.Dense							)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]							):
        __lowerCamelCase   ,     __lowerCamelCase:				Tuple     =	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           __lowerCamelCase:				int     =	model_class(_A							)
           __lowerCamelCase:				Union[str, Any]     =	inspect.signature(model.call							)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           __lowerCamelCase:				Tuple     =	[*signature.parameters.keys()]

           __lowerCamelCase:				Union[str, Any]     =	["""pixel_values"""]
           self.assertListEqual(arg_names[:1]    ,	_A							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        __lowerCamelCase:				str     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_A							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase:				Union[str, Any]     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*_A							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict							):
        __lowerCamelCase:				str     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_A							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				Any=False							):
        __lowerCamelCase:				Tuple     =	super()._prepare_for_class(_A    ,	_A    ,	return_labels=_A							)

        if return_labels:
           if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call							).parameters:
              del inputs_dict["labels"]

        return inputs_dict







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:				int     =	TFDeiTModel.from_pretrained(_A							)
           self.assertIsNotNone(_A							)



def     __lowerCAmelCase						(							)       ->							int:
   __lowerCamelCase:				List[str]     =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image







@require_tf
@require_vision
class        a					(			unittest.TestCase   ):





     @cached_property
     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]							):
        return (
            DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""							)
            if is_vision_available()
            else None
        )







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase:				Optional[int]     =	TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""							)

        __lowerCamelCase:				Optional[Any]     =	self.default_image_processor
        __lowerCamelCase:				int     =	prepare_img()
        __lowerCamelCase:				Union[str, Any]     =	image_processor(images=_A    ,	return_tensors="""tf"""							)

        # forward pass
        __lowerCamelCase:				int     =	model(**_A							)

        # verify the logits
        __lowerCamelCase:				Any     =	tf.TensorShape((1, 1000)							)
        self.assertEqual(outputs.logits.shape    ,	_A							)

        __lowerCamelCase:				int     =	tf.constant([-1.0266, 0.1912, -1.2861]							)

        self.assertTrue(np.allclose(outputs.logits[0, :3]    ,	_A    ,	atol=1E-4							)							)






from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_pt_objects import *  # noqa F403
else:
   from .scheduling_consistency_models import CMStochasticIterativeScheduler
   from .scheduling_ddim import DDIMScheduler
   from .scheduling_ddim_inverse import DDIMInverseScheduler
   from .scheduling_ddim_parallel import DDIMParallelScheduler
   from .scheduling_ddpm import DDPMScheduler
   from .scheduling_ddpm_parallel import DDPMParallelScheduler
   from .scheduling_deis_multistep import DEISMultistepScheduler
   from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
   from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
   from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
   from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
   from .scheduling_euler_discrete import EulerDiscreteScheduler
   from .scheduling_heun_discrete import HeunDiscreteScheduler
   from .scheduling_ipndm import IPNDMScheduler
   from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
   from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
   from .scheduling_karras_ve import KarrasVeScheduler
   from .scheduling_pndm import PNDMScheduler
   from .scheduling_repaint import RePaintScheduler
   from .scheduling_sde_ve import ScoreSdeVeScheduler
   from .scheduling_sde_vp import ScoreSdeVpScheduler
   from .scheduling_unclip import UnCLIPScheduler
   from .scheduling_unipc_multistep import UniPCMultistepScheduler
   from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
   from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_flax_objects import *  # noqa F403
else:
   from .scheduling_ddim_flax import FlaxDDIMScheduler
   from .scheduling_ddpm_flax import FlaxDDPMScheduler
   from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
   from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
   from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
   from .scheduling_pndm_flax import FlaxPNDMScheduler
   from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
   from .scheduling_utils_flax import (
       FlaxKarrasDiffusionSchedulers,
       FlaxSchedulerMixin,
       FlaxSchedulerOutput,
       broadcast_to_shape_from_left,
   )


try:
   if not (is_torch_available() and is_scipy_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
   from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
   if not (is_torch_available() and is_torchsde_available()):
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
   from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler


