
"""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 				A__ :

		def __init__(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=13 ,	_SCREAMING_SNAKE_CASE=30 ,	_SCREAMING_SNAKE_CASE=2 ,	_SCREAMING_SNAKE_CASE=3 ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE=True ,	_SCREAMING_SNAKE_CASE=32 ,	_SCREAMING_SNAKE_CASE=2 ,	_SCREAMING_SNAKE_CASE=4 ,	_SCREAMING_SNAKE_CASE=37 ,	_SCREAMING_SNAKE_CASE="gelu" ,	_SCREAMING_SNAKE_CASE=0.1 ,	_SCREAMING_SNAKE_CASE=0.1 ,	_SCREAMING_SNAKE_CASE=10 ,	_SCREAMING_SNAKE_CASE=0.02 ,	_SCREAMING_SNAKE_CASE=3 ,	_SCREAMING_SNAKE_CASE=None ,	_SCREAMING_SNAKE_CASE=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 							__lowerCamelCase							(   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 							__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=_SCREAMING_SNAKE_CASE ,	initializer_range=self.initializer_range ,	encoder_stride=self.encoder_stride ,	)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase		    =   TFDeiTModel(config=_SCREAMING_SNAKE_CASE				)
			__lowerCAmelCase		    =   model(_SCREAMING_SNAKE_CASE				)
			self.parent.assertEqual(result.last_hidden_state.shape ,	(self.batch_size, self.seq_length, self.hidden_size)				)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE				):
			__lowerCAmelCase		    =   TFDeiTForMaskedImageModeling(config=_SCREAMING_SNAKE_CASE				)
			__lowerCAmelCase		    =   model(_SCREAMING_SNAKE_CASE				)
			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(_SCREAMING_SNAKE_CASE				)

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

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

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

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







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




@require_tf
class 				A__ (			_lowerCamelCase ,  _lowerCamelCase ,  unittest.TestCase):
		A_		: Optional[Any]            =			(
		    (
		        TFDeiTModel,
		        TFDeiTForImageClassification,
		        TFDeiTForImageClassificationWithTeacher,
		        TFDeiTForMaskedImageModeling,
		    )
		    if is_tf_available()
		    else ()
		)
		A_		: str            =			(
		    {
		        'feature-extraction': TFDeiTModel,
		        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
		    }
		    if is_tf_available()
		    else {}
		)

		A_		: Tuple            =			False
		A_		: List[str]            =			False
		A_		: List[str]            =			False
		A_		: Dict            =			False

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase		    =   TFDeiTModelTester(self				)
			__lowerCAmelCase		    =   ConfigTester(self ,	config_class=_SCREAMING_SNAKE_CASE ,	has_text_modality=_SCREAMING_SNAKE_CASE ,	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				):
			__lowerCAmelCase		    =   self.model_tester.prepare_config_and_inputs_for_common()

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

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase		    =   self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
				__lowerCAmelCase		    =   model_class(_SCREAMING_SNAKE_CASE				)
				__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] ,	_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_masked_image_modeling(*_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self				):
			__lowerCAmelCase		    =   self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE				)

		def 							__lowerCamelCase							(   self ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE=False				):
			__lowerCAmelCase		    =   super()._prepare_for_class(_SCREAMING_SNAKE_CASE ,	_SCREAMING_SNAKE_CASE ,	return_labels=_SCREAMING_SNAKE_CASE				)

			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]:
				__lowerCAmelCase		    =   TFDeiTModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
				self.assertIsNotNone(_SCREAMING_SNAKE_CASE				)



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




@require_tf
@require_vision
class 				A__ (			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				):
			__lowerCAmelCase		    =   TFDeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224'				)

			__lowerCAmelCase		    =   self.default_image_processor
			__lowerCAmelCase		    =   prepare_img()
			__lowerCAmelCase		    =   image_processor(images=_SCREAMING_SNAKE_CASE ,	return_tensors='tf'				)

			# forward pass
			__lowerCAmelCase		    =   model(**_SCREAMING_SNAKE_CASE				)

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

			__lowerCAmelCase		    =   tf.constant([-1.0266, 0.1912, -1.2861]				)

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

"""simple docstring"""







import argparse
import os
import pickle
import sys

import torch

from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl
from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils
from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()

# We do this to be able to load python 2 datasets pickles
# See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918
lowerCamelCase__           =	data_utils.TransfoXLTokenizer
lowerCamelCase__           =	data_utils.TransfoXLCorpus
lowerCamelCase__           =	data_utils
lowerCamelCase__           =	data_utils
def 					__lowerCAmelCase       (_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase	):
	if transfo_xl_dataset_file:
		# Convert a pre-processed corpus (see original TensorFlow repo)
		with open(_UpperCamelCase ,						'rb'	) as fp:
			__lowerCAmelCase    :		int		    =   pickle.load(_UpperCamelCase ,						encoding='latin1'	)
		# Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term)
		__lowerCAmelCase    :		Any		    =   pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file']
		print(F"Save vocabulary to {pytorch_vocab_dump_path}"	)
		__lowerCAmelCase    :		Optional[Any]		    =   corpus.vocab.__dict__
		torch.save(_UpperCamelCase ,						_UpperCamelCase	)

		__lowerCAmelCase    :		Dict		    =   corpus.__dict__
		corpus_dict_no_vocab.pop('vocab' ,						_UpperCamelCase	)
		__lowerCAmelCase    :		List[str]		    =   pytorch_dump_folder_path + '/' + CORPUS_NAME
		print(F"Save dataset to {pytorch_dataset_dump_path}"	)
		torch.save(_UpperCamelCase ,						_UpperCamelCase	)

	if tf_checkpoint_path:
		# Convert a pre-trained TensorFlow model
		__lowerCAmelCase    :		Tuple		    =   os.path.abspath(_UpperCamelCase	)
		__lowerCAmelCase    :		List[Any]		    =   os.path.abspath(_UpperCamelCase	)

		print(F"Converting Transformer XL checkpoint from {tf_path} with config at {config_path}."	)
		# Initialise PyTorch model
		if transfo_xl_config_file == "":
			__lowerCAmelCase    :		Any		    =   TransfoXLConfig()
		else:
			__lowerCAmelCase    :		str		    =   TransfoXLConfig.from_json_file(_UpperCamelCase	)
		print(F"Building PyTorch model from configuration: {config}"	)
		__lowerCAmelCase    :		Optional[Any]		    =   TransfoXLLMHeadModel(_UpperCamelCase	)

		__lowerCAmelCase    :		Dict		    =   load_tf_weights_in_transfo_xl(_UpperCamelCase ,						_UpperCamelCase ,						_UpperCamelCase	)
		# Save pytorch-model
		__lowerCAmelCase    :		str		    =   os.path.join(_UpperCamelCase ,						_UpperCamelCase	)
		__lowerCAmelCase    :		Tuple		    =   os.path.join(_UpperCamelCase ,						_UpperCamelCase	)
		print(F"Save PyTorch model to {os.path.abspath(_UpperCamelCase	)}"	)
		torch.save(model.state_dict() ,						_UpperCamelCase	)
		print(F"Save configuration file to {os.path.abspath(_UpperCamelCase	)}"	)
		with open(_UpperCamelCase ,						'w' ,						encoding='utf-8'	) as f:
			f.write(config.to_json_string()	)


if __name__ == "__main__":
							lowerCamelCase__           =	argparse.ArgumentParser()
							parser.add_argument(
							    """--pytorch_dump_folder_path""",
							    default=None,
							    type=str,
							    required=True,
							    help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
							)
							parser.add_argument(
							    """--tf_checkpoint_path""",
							    default="""""",
							    type=str,
							    help="""An optional path to a TensorFlow checkpoint path to be converted.""",
							)
							parser.add_argument(
							    """--transfo_xl_config_file""",
							    default="""""",
							    type=str,
							    help=(
							        """An optional config json file corresponding to the pre-trained BERT model. \n"""
							        """This specifies the model architecture."""
							    ),
							)
							parser.add_argument(
							    """--transfo_xl_dataset_file""",
							    default="""""",
							    type=str,
							    help="""An optional dataset file to be converted in a vocabulary.""",
							)
							lowerCamelCase__           =	parser.parse_args()
							convert_transfo_xl_checkpoint_to_pytorch(
							    args.tf_checkpoint_path,
							    args.transfo_xl_config_file,
							    args.pytorch_dump_folder_path,
							    args.transfo_xl_dataset_file,
							)