

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       __snake_case  :

  def __init__(					self						,		_A						,		_A=13						,		_A=30						,		_A=2						,		_A=3						,		_A=True						,		_A=True						,		_A=32						,		_A=2						,		_A=4						,		_A=37						,		_A="gelu"						,		_A=0.1						,		_A=0.1						,		_A=10						,		_A=0.0_2						,		_A=3						,		_A=None						,		_A=2						,		):
      SCREAMING_SNAKE_CASE_									=						parent
      SCREAMING_SNAKE_CASE_									=						batch_size
      SCREAMING_SNAKE_CASE_									=						image_size
      SCREAMING_SNAKE_CASE_									=						patch_size
      SCREAMING_SNAKE_CASE_									=						num_channels
      SCREAMING_SNAKE_CASE_									=						is_training
      SCREAMING_SNAKE_CASE_									=						use_labels
      SCREAMING_SNAKE_CASE_									=						hidden_size
      SCREAMING_SNAKE_CASE_									=						num_hidden_layers
      SCREAMING_SNAKE_CASE_									=						num_attention_heads
      SCREAMING_SNAKE_CASE_									=						intermediate_size
      SCREAMING_SNAKE_CASE_									=						hidden_act
      SCREAMING_SNAKE_CASE_									=						hidden_dropout_prob
      SCREAMING_SNAKE_CASE_									=						attention_probs_dropout_prob
      SCREAMING_SNAKE_CASE_									=						type_sequence_label_size
      SCREAMING_SNAKE_CASE_									=						initializer_range
      SCREAMING_SNAKE_CASE_									=						scope
      SCREAMING_SNAKE_CASE_									=						encoder_stride

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

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

      SCREAMING_SNAKE_CASE_									=						self.get_config()

      return config, pixel_values, labels

  def 						lowerCAmelCase__     (					self):
      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 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A):
      SCREAMING_SNAKE_CASE_									=						TFDeiTModel(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.last_hidden_state.shape						,		(self.batch_size, self.seq_length, self.hidden_size))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A):
      SCREAMING_SNAKE_CASE_									=						TFDeiTForMaskedImageModeling(config=_A)
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(
          result.reconstruction.shape						,		(self.batch_size, self.num_channels, self.image_size, self.image_size))

      # test greyscale images
      SCREAMING_SNAKE_CASE_									=						1
      SCREAMING_SNAKE_CASE_									=						TFDeiTForMaskedImageModeling(_A)

      SCREAMING_SNAKE_CASE_									=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
      SCREAMING_SNAKE_CASE_									=						model(_A)
      self.parent.assertEqual(result.reconstruction.shape						,		(self.batch_size, 1, self.image_size, self.image_size))

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A):
      SCREAMING_SNAKE_CASE_									=						self.type_sequence_label_size
      SCREAMING_SNAKE_CASE_									=						TFDeiTForImageClassification(_A)
      SCREAMING_SNAKE_CASE_									=						model(_A						,		labels=_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.type_sequence_label_size))

      # test greyscale images
      SCREAMING_SNAKE_CASE_									=						1
      SCREAMING_SNAKE_CASE_									=						TFDeiTForImageClassification(_A)

      SCREAMING_SNAKE_CASE_									=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
      SCREAMING_SNAKE_CASE_									=						model(_A						,		labels=_A)
      self.parent.assertEqual(result.logits.shape						,		(self.batch_size, self.type_sequence_label_size))


  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.prepare_config_and_inputs()
      SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_									=						config_and_inputs
      SCREAMING_SNAKE_CASE_									=						{'pixel_values': pixel_values}
      return config, inputs_dict






@require_tf
class       __snake_case  (    lowerCAmelCase__     , lowerCAmelCase__     , unittest.TestCase       ):
  __lowerCAmelCase     :	Any						 =  (
      (
          TFDeiTModel,
          TFDeiTForImageClassification,
          TFDeiTForImageClassificationWithTeacher,
          TFDeiTForMaskedImageModeling,
      )
      if is_tf_available()
      else ()
  )
  __lowerCAmelCase     :	str						 =  (
      {
          'feature-extraction': TFDeiTModel,
          'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
      }
      if is_tf_available()
      else {}
  )

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

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						TFDeiTModelTester(self)
      SCREAMING_SNAKE_CASE_									=						ConfigTester(self						,		config_class=_A						,		has_text_modality=_A						,		hidden_size=37)

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

  @unittest.skip(reason='DeiT does not use inputs_embeds')
  def 						lowerCAmelCase__     (					self):
      pass

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          SCREAMING_SNAKE_CASE_									=						model_class(_A)
          self.assertIsInstance(model.get_input_embeddings()						,		(tf.keras.layers.Layer))
          SCREAMING_SNAKE_CASE_									=						model.get_output_embeddings()
          self.assertTrue(x is None or isinstance(_A						,		tf.keras.layers.Dense))

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_							,			SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
          SCREAMING_SNAKE_CASE_									=						model_class(_A)
          SCREAMING_SNAKE_CASE_									=						inspect.signature(model.call)
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          SCREAMING_SNAKE_CASE_									=						[*signature.parameters.keys()]

          SCREAMING_SNAKE_CASE_									=						['pixel_values']
          self.assertListEqual(arg_names[:1]						,		_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*_A)

  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_A)

  def 						lowerCAmelCase__     (					self						,		_A						,		_A						,		_A=False):
      SCREAMING_SNAKE_CASE_									=						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 						lowerCAmelCase__     (					self):
      for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          SCREAMING_SNAKE_CASE_									=						TFDeiTModel.from_pretrained(_A)
          self.assertIsNotNone(_A)






def 					_UpperCAmelCase       (  ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
    return image





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

  @cached_property
  def 						lowerCAmelCase__     (					self):
      return (
          DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224')
          if is_vision_available()
          else None
      )


  @slow
  def 						lowerCAmelCase__     (					self):
      SCREAMING_SNAKE_CASE_									=						TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224')

      SCREAMING_SNAKE_CASE_									=						self.default_image_processor
      SCREAMING_SNAKE_CASE_									=						prepare_img()
      SCREAMING_SNAKE_CASE_									=						image_processor(images=_A						,		return_tensors='tf')

      # forward pass
      SCREAMING_SNAKE_CASE_									=						model(**_A)

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

      SCREAMING_SNAKE_CASE_									=						tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1])

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





from typing import List

import numpy as np


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		dict       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						{key: len(_SCREAMING_SNAKE_CASE       ) for key, value in gen_kwargs.items() if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )}
    if len(set(lists_lengths.values()       )       ) > 1:
        raise RuntimeError(
            (
                'Sharding is ambiguous for this dataset: '
                + 'we found several data sources lists of different lengths, and we don\'t know over which list we should parallelize:\n'
                + '\n'.join(f"""\t- key {key} has length {length}""" for key, length in lists_lengths.items()       )
                + '\nTo fix this, check the \'gen_kwargs\' and make sure to use lists only for data sources, '
                + 'and use tuples otherwise. In the end there should only be one single list, or several lists with the same length.'
            )       )
    SCREAMING_SNAKE_CASE_									=						max(lists_lengths.values() ,   default=0       )
    return max(1 ,   _SCREAMING_SNAKE_CASE       )


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		int ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						[]
    for group_idx in range(_SCREAMING_SNAKE_CASE       ):
        SCREAMING_SNAKE_CASE_									=						num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
        if num_shards_to_add == 0:
            break
        SCREAMING_SNAKE_CASE_									=						shards_indices_per_group[-1].stop if shards_indices_per_group else 0
        SCREAMING_SNAKE_CASE_									=						range(_SCREAMING_SNAKE_CASE ,   start + num_shards_to_add       )
        shards_indices_per_group.append(_SCREAMING_SNAKE_CASE       )
    return shards_indices_per_group


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		dict ,   _SCREAMING_SNAKE_CASE					:		int       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						_number_of_shards_in_gen_kwargs(_SCREAMING_SNAKE_CASE       )
    if num_shards == 1:
        return [dict(_SCREAMING_SNAKE_CASE       )]
    else:
        SCREAMING_SNAKE_CASE_									=						_distribute_shards(num_shards=_SCREAMING_SNAKE_CASE ,   max_num_jobs=_SCREAMING_SNAKE_CASE       )
        return [
            {
                key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
                if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )
                else value
                for key, value in gen_kwargs.items()
            }
            for group_idx in range(len(_SCREAMING_SNAKE_CASE       )       )
        ]


def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		List[dict]       ):





    """simple docstring"""


    return {
        key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
        if isinstance(gen_kwargs_list[0][key] ,   _SCREAMING_SNAKE_CASE       )
        else gen_kwargs_list[0][key]
        for key in gen_kwargs_list[0]
    }





def 					_UpperCAmelCase       (  _SCREAMING_SNAKE_CASE					:		np.random.Generator ,   _SCREAMING_SNAKE_CASE					:		dict       ):





    """simple docstring"""


    SCREAMING_SNAKE_CASE_									=						{len(_SCREAMING_SNAKE_CASE       ) for value in gen_kwargs.values() if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       )}
    SCREAMING_SNAKE_CASE_									=						{}
    for size in list_sizes:
        SCREAMING_SNAKE_CASE_									=						list(range(_SCREAMING_SNAKE_CASE       )       )
        rng.shuffle(indices_per_size[size]       )
    # Now let's copy the gen_kwargs and shuffle the lists based on their sizes
    SCREAMING_SNAKE_CASE_									=						dict(_SCREAMING_SNAKE_CASE       )
    for key, value in shuffled_kwargs.items():
        if isinstance(_SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE       ):
            SCREAMING_SNAKE_CASE_									=						[value[i] for i in indices_per_size[len(_SCREAMING_SNAKE_CASE       )]]
    return shuffled_kwargs


