


"""simple docstring"""


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 						_UpperCamelCase						:
							'''simple docstring'''







							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					,     ):
										__lowerCAmelCase       					=    parent
										__lowerCAmelCase       					=    batch_size
										__lowerCAmelCase       					=    image_size
										__lowerCAmelCase       					=    patch_size
										__lowerCAmelCase       					=    num_channels
										__lowerCAmelCase       					=    is_training
										__lowerCAmelCase       					=    use_labels
										__lowerCAmelCase       					=    hidden_size
										__lowerCAmelCase       					=    num_hidden_layers
										__lowerCAmelCase       					=    num_attention_heads
										__lowerCAmelCase       					=    intermediate_size
										__lowerCAmelCase       					=    hidden_act
										__lowerCAmelCase       					=    hidden_dropout_prob
										__lowerCAmelCase       					=    attention_probs_dropout_prob
										__lowerCAmelCase       					=    type_sequence_label_size
										__lowerCAmelCase       					=    initializer_range
										__lowerCAmelCase       					=    scope
										__lowerCAmelCase       					=    encoder_stride

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

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

										__lowerCAmelCase       					=    self.get_config()

										return config, pixel_values, labels

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

							def     snake_case       (  self					,     __a					,     __a					,     __a			):
										__lowerCAmelCase       					=    TFDeiTForMaskedImageModeling(config=__a			)
										__lowerCAmelCase       					=    model(__a			)
										self.parent.assertEqual(
										    result.reconstruction.shape					,     (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

										# test greyscale images
										__lowerCAmelCase       					=    1
										__lowerCAmelCase       					=    TFDeiTForMaskedImageModeling(__a			)

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

							def     snake_case       (  self					,     __a					,     __a					,     __a			):
										__lowerCAmelCase       					=    self.type_sequence_label_size
										__lowerCAmelCase       					=    TFDeiTForImageClassification(__a			)
										__lowerCAmelCase       					=    model(__a					,     labels=__a			)
										self.parent.assertEqual(result.logits.shape					,     (self.batch_size, self.type_sequence_label_size)			)

										# test greyscale images
										__lowerCAmelCase       					=    1
										__lowerCAmelCase       					=    TFDeiTForImageClassification(__a			)

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



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										__lowerCAmelCase					,			__lowerCAmelCase					,			__lowerCAmelCase       					=    config_and_inputs
										__lowerCAmelCase       					=    {"pixel_values": pixel_values}
										return config, inputs_dict
@require_tf
class 						_UpperCamelCase						(     lowerCAmelCase__ ,lowerCAmelCase__ ,unittest.TestCase	):
							'''simple docstring'''







							__UpperCAmelCase		:					Tuple          =(
							    (
							        TFDeiTModel,
							        TFDeiTForImageClassification,
							        TFDeiTForImageClassificationWithTeacher,
							        TFDeiTForMaskedImageModeling,
							    )
							    if is_tf_available()
							    else ()
							)
							__UpperCAmelCase		:					Tuple          =(
							    {
							        """feature-extraction""": TFDeiTModel,
							        """image-classification""": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
							    }
							    if is_tf_available()
							    else {}
							)

							__UpperCAmelCase		:					Tuple          =False
							__UpperCAmelCase		:					Dict          =False
							__UpperCAmelCase		:					List[Any]          =False
							__UpperCAmelCase		:					str          =False

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFDeiTModelTester(self			)
										__lowerCAmelCase       					=    ConfigTester(self					,     config_class=__a					,     has_text_modality=__a					,     hidden_size=37			)

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

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

							def     snake_case       (  self			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs_for_common()

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

							def     snake_case       (  self			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs_for_common()

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

													__lowerCAmelCase       					=    ["pixel_values"]
													self.assertListEqual(arg_names[:1]					,     __a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__a			)

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


def _lowerCamelCase			(	):

			'''simple docstring'''




			__lowerCAmelCase       					=    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
			return image


@require_tf
@require_vision
class 						_UpperCamelCase						(     unittest.TestCase	):
							'''simple docstring'''







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



							@slow
							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"			)

										__lowerCAmelCase       					=    self.default_image_processor
										__lowerCAmelCase       					=    prepare_img()
										__lowerCAmelCase       					=    image_processor(images=__a					,     return_tensors="tf"			)

										# forward pass
										__lowerCAmelCase       					=    model(**__a			)

										# verify the logits
										__lowerCAmelCase       					=    tf.TensorShape((1, 10_00)			)
										self.assertEqual(outputs.logits.shape					,     __a			)

										__lowerCAmelCase       					=    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			)			)








"""simple docstring"""


import tensorflow as tf

from ...tf_utils import shape_list
class 						_UpperCamelCase						(     tf.keras.layers.Layer	):
							'''simple docstring'''







							def __init__(  self					,     __a					,     __a					,     __a					,     __a					,     __a=1					,     __a=False					,     **__a			):
										super().__init__(**__a			)

										__lowerCAmelCase       					=    vocab_size
										__lowerCAmelCase       					=    d_embed
										__lowerCAmelCase       					=    d_proj

										__lowerCAmelCase       					=    cutoffs + [vocab_size]
										__lowerCAmelCase       					=    [0] + self.cutoffs
										__lowerCAmelCase       					=    div_val

										__lowerCAmelCase       					=    self.cutoffs[0]
										__lowerCAmelCase       					=    len(self.cutoffs			) - 1
										__lowerCAmelCase       					=    self.shortlist_size + self.n_clusters
										__lowerCAmelCase       					=    keep_order

										__lowerCAmelCase       					=    []
										__lowerCAmelCase       					=    []

							def     snake_case       (  self					,     __a			):
										if self.n_clusters > 0:
													__lowerCAmelCase       					=    self.add_weight(
													    shape=(self.n_clusters, self.d_embed)					,     initializer="zeros"					,     trainable=__a					,     name="cluster_weight"			)
													__lowerCAmelCase       					=    self.add_weight(
													    shape=(self.n_clusters,)					,     initializer="zeros"					,     trainable=__a					,     name="cluster_bias"			)

										if self.div_val == 1:
													for i in range(len(self.cutoffs			)			):
																if self.d_proj != self.d_embed:
																			__lowerCAmelCase       					=    self.add_weight(
																			    shape=(self.d_embed, self.d_proj)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_projs_._{i}"					,     )
																			self.out_projs.append(__a			)
																else:
																			self.out_projs.append(__a			)
																__lowerCAmelCase       					=    self.add_weight(
																    shape=(self.vocab_size, self.d_embed)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_layers_._{i}_._weight"					,     )
																__lowerCAmelCase       					=    self.add_weight(
																    shape=(self.vocab_size,)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_layers_._{i}_._bias"					,     )
																self.out_layers.append((weight, bias)			)
										else:
													for i in range(len(self.cutoffs			)			):
																__lowerCAmelCase					,			__lowerCAmelCase       					=    self.cutoff_ends[i], self.cutoff_ends[i + 1]
																__lowerCAmelCase       					=    self.d_embed // (self.div_val**i)

																__lowerCAmelCase       					=    self.add_weight(
																    shape=(d_emb_i, self.d_proj)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_projs_._{i}"			)
																self.out_projs.append(__a			)
																__lowerCAmelCase       					=    self.add_weight(
																    shape=(r_idx - l_idx, d_emb_i)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_layers_._{i}_._weight"					,     )
																__lowerCAmelCase       					=    self.add_weight(
																    shape=(r_idx - l_idx,)					,     initializer="zeros"					,     trainable=__a					,     name=f"out_layers_._{i}_._bias"					,     )
																self.out_layers.append((weight, bias)			)
										super().build(__a			)

							@staticmethod
							def     snake_case       (  __a					,     __a					,     __a					,     __a=None			):
										__lowerCAmelCase       					=    x
										if proj is not None:
													__lowerCAmelCase       					=    tf.einsum("ibd,ed->ibe"					,     __a					,     __a			)
										return tf.einsum("ibd,nd->ibn"					,     __a					,     __a			) + b

							@staticmethod
							def     snake_case       (  __a					,     __a			):
										__lowerCAmelCase       					=    shape_list(__a			)
										__lowerCAmelCase       					=    tf.range(lp_size[0]					,     dtype=target.dtype			)
										__lowerCAmelCase       					=    tf.stack([r, target]					,     1			)
										return tf.gather_nd(__a					,     __a			)



							def     snake_case       (  self					,     __a					,     __a					,     __a=True					,     __a=False			):
										__lowerCAmelCase       					=    0
										if self.n_clusters == 0:
													__lowerCAmelCase       					=    self._logit(__a					,     self.out_layers[0][0]					,     self.out_layers[0][1]					,     self.out_projs[0]			)
													if target is not None:
																__lowerCAmelCase       					=    tf.nn.sparse_softmax_cross_entropy_with_logits(labels=__a					,     logits=__a			)
													__lowerCAmelCase       					=    tf.nn.log_softmax(__a					,     axis=-1			)
										else:
													__lowerCAmelCase       					=    shape_list(__a			)
													__lowerCAmelCase       					=    []
													__lowerCAmelCase       					=    tf.zeros(hidden_sizes[:2]			)
													for i in range(len(self.cutoffs			)			):
																__lowerCAmelCase					,			__lowerCAmelCase       					=    self.cutoff_ends[i], self.cutoff_ends[i + 1]
																if target is not None:
																			__lowerCAmelCase       					=    (target >= l_idx) & (target < r_idx)
																			__lowerCAmelCase       					=    tf.where(__a			)
																			__lowerCAmelCase       					=    tf.boolean_mask(__a					,     __a			) - l_idx

																if self.div_val == 1:
																			__lowerCAmelCase       					=    self.out_layers[0][0][l_idx:r_idx]
																			__lowerCAmelCase       					=    self.out_layers[0][1][l_idx:r_idx]
																else:
																			__lowerCAmelCase       					=    self.out_layers[i][0]
																			__lowerCAmelCase       					=    self.out_layers[i][1]

																if i == 0:
																			__lowerCAmelCase       					=    tf.concat([cur_W, self.cluster_weight]					,     0			)
																			__lowerCAmelCase       					=    tf.concat([cur_b, self.cluster_bias]					,     0			)

																			__lowerCAmelCase       					=    self._logit(__a					,     __a					,     __a					,     self.out_projs[0]			)
																			__lowerCAmelCase       					=    tf.nn.log_softmax(__a			)
																			out.append(head_logprob[..., : self.cutoffs[0]]			)
																			if target is not None:
																						__lowerCAmelCase       					=    tf.boolean_mask(__a					,     __a			)
																						__lowerCAmelCase       					=    self._gather_logprob(__a					,     __a			)
																else:
																			__lowerCAmelCase       					=    self._logit(__a					,     __a					,     __a					,     self.out_projs[i]			)
																			__lowerCAmelCase       					=    tf.nn.log_softmax(__a			)
																			__lowerCAmelCase       					=    self.cutoffs[0] + i - 1  # No probability for the head cluster
																			__lowerCAmelCase       					=    head_logprob[..., cluster_prob_idx, None] + tail_logprob
																			out.append(__a			)
																			if target is not None:
																						__lowerCAmelCase       					=    tf.boolean_mask(__a					,     __a			)
																						__lowerCAmelCase       					=    tf.boolean_mask(__a					,     __a			)
																						__lowerCAmelCase       					=    self._gather_logprob(__a					,     __a			)
																						cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
																if target is not None:
																			loss += tf.scatter_nd(__a					,     -cur_logprob					,     shape_list(__a			)			)
													__lowerCAmelCase       					=    tf.concat(__a					,     axis=-1			)

										if target is not None:
													if return_mean:
																__lowerCAmelCase       					=    tf.reduce_mean(__a			)
													# Add the training-time loss value to the layer using `self.add_loss()`.
													self.add_loss(__a			)

													# Log the loss as a metric (we could log arbitrary metrics,
													# including different metrics for training and inference.
													self.add_metric(__a					,     name=self.name					,     aggregation="mean" if return_mean else ""			)

										return out




