
from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TFTransfoXLForSequenceClassification,
					    TFTransfoXLLMHeadModel,
					    TFTransfoXLModel,
					)





class 				UpperCAmelCase :




	'''simple docstring'''





	def __init__(			self   :					Dict				,A   :					Optional[Any]				,):
					__A       =					parent
					__A       =					13
					__A       =					7
					__A       =					30
					__A       =					self.seq_length + self.mem_len
					__A       =					15
					__A       =					True
					__A       =					True
					__A       =					99
					__A       =					[10, 50, 80]
					__A       =					32
					__A       =					32
					__A       =					4
					__A       =					8
					__A       =					1_28
					__A       =					2
					__A       =					2
					__A       =					None
					__A       =					1
					__A       =					0
					__A       =					3
					__A       =					self.vocab_size - 1
					__A       =					0.01






	def 							UpperCamelCase_    (			self   :					Union[str, Any]					):
					__A       =					ids_tensor([self.batch_size, self.seq_length]				,self.vocab_size					)
					__A       =					ids_tensor([self.batch_size, self.seq_length]				,self.vocab_size					)

					__A       =					None
					if self.use_labels:
									__A       =					ids_tensor([self.batch_size, self.seq_length]				,self.vocab_size					)

					__A       =					TransfoXLConfig(
					    vocab_size=self.vocab_size				,mem_len=self.mem_len				,clamp_len=self.clamp_len				,cutoffs=self.cutoffs				,d_model=self.hidden_size				,d_embed=self.d_embed				,n_head=self.num_attention_heads				,d_head=self.d_head				,d_inner=self.d_inner				,div_val=self.div_val				,n_layer=self.num_hidden_layers				,eos_token_id=self.eos_token_id				,pad_token_id=self.vocab_size - 1				,init_range=self.init_range				,num_labels=self.num_labels				,)

					return (config, input_ids_a, input_ids_a, lm_labels)






	def 							UpperCamelCase_    (			self   :					Any					):
					random.seed(self.seed					)
					tf.random.set_seed(self.seed					)






	def 							UpperCamelCase_    (			self   :					str				,A   :					List[Any]				,A   :					str				,A   :					Optional[Any]				,A   :					Union[str, Any]					):
					__A       =					TFTransfoXLModel(A					)

					__A     ,				__A       =					model(A					).to_tuple()

					__A       =					{"input_ids": input_ids_a, "mems": mems_a}

					__A     ,				__A       =					model(A					).to_tuple()

					self.parent.assertEqual(hidden_states_a.shape				,(self.batch_size, self.seq_length, self.hidden_size)					)
					self.parent.assertEqual(hidden_states_a.shape				,(self.batch_size, self.seq_length, self.hidden_size)					)
					self.parent.assertListEqual(
					    [mem.shape for mem in mems_a]				,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,)
					self.parent.assertListEqual(
					    [mem.shape for mem in mems_a]				,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,)






	def 							UpperCamelCase_    (			self   :					Optional[Any]				,A   :					Dict				,A   :					Any				,A   :					Any				,A   :					Optional[Any]					):
					__A       =					TFTransfoXLLMHeadModel(A					)

					__A     ,				__A       =					model(A					).to_tuple()

					__A       =					{"input_ids": input_ids_a, "labels": lm_labels}
					__A     ,				__A       =					model(A					).to_tuple()

					__A     ,				__A       =					model([input_ids_a, mems_a]					).to_tuple()

					__A       =					{"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels}

					__A     ,				__A       =					model(A					).to_tuple()

					self.parent.assertEqual(lm_logits_a.shape				,(self.batch_size, self.seq_length, self.vocab_size)					)
					self.parent.assertListEqual(
					    [mem.shape for mem in mems_a]				,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,)

					self.parent.assertEqual(lm_logits_a.shape				,(self.batch_size, self.seq_length, self.vocab_size)					)
					self.parent.assertListEqual(
					    [mem.shape for mem in mems_a]				,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers				,)






	def 							UpperCamelCase_    (			self   :					Optional[Any]				,A   :					Tuple				,A   :					str				,A   :					Union[str, Any]				,A   :					Optional[int]					):
					__A       =					TFTransfoXLForSequenceClassification(A					)
					__A       =					model(A					)
					self.parent.assertEqual(result.logits.shape				,(self.batch_size, self.num_labels)					)







	def 							UpperCamelCase_    (			self   :					int					):
					__A       =					self.prepare_config_and_inputs()
					((__A)     ,				(__A)     ,				(__A)     ,				(__A))       =					config_and_inputs
					__A       =					{"input_ids": input_ids_a}
					return config, inputs_dict





@require_tf
class 				UpperCAmelCase (    __SCREAMING_SNAKE_CASE     ,     __SCREAMING_SNAKE_CASE     ,     unittest.TestCase    ):




	'''simple docstring'''





	snake_case_          =	(
	    (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
	)
	snake_case_          =	() if is_tf_available() else ()
	snake_case_          =	(
	    {
	        "feature-extraction": TFTransfoXLModel,
	        "text-classification": TFTransfoXLForSequenceClassification,
	        "text-generation": TFTransfoXLLMHeadModel,
	        "zero-shot": TFTransfoXLForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)
	# TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
	snake_case_          =	False
	snake_case_          =	False
	snake_case_          =	False
	snake_case_          =	False






	def 							UpperCamelCase_    (			self   :					List[str]				,A   :					str				,A   :					Optional[Any]				,A   :					Any				,A   :					Optional[Any]				,A   :					List[Any]					):
					if pipeline_test_casse_name == "TextGenerationPipelineTests":
									# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
									# `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
									# tokenizer.
									return True

					return False






	def 							UpperCamelCase_    (			self   :					Optional[Any]					):
					__A       =					TFTransfoXLModelTester(self					)
					__A       =					ConfigTester(self				,config_class=A				,d_embed=37					)






	def 							UpperCamelCase_    (			self   :					Any					):
					self.config_tester.run_common_tests()






	def 							UpperCamelCase_    (			self   :					Tuple					):
					self.model_tester.set_seed()
					__A       =					self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_transfo_xl_model(*A					)






	def 							UpperCamelCase_    (			self   :					str					):
					self.model_tester.set_seed()
					__A       =					self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_transfo_xl_lm_head(*A					)






	def 							UpperCamelCase_    (			self   :					int					):
					__A       =					self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*A					)






	def 							UpperCamelCase_    (			self   :					Tuple					):
					__A     ,				__A       =					self.model_tester.prepare_config_and_inputs_for_common()
					__A       =					[TFTransfoXLForSequenceClassification]

					for model_class in self.all_model_classes:
									__A       =					model_class(A					)
									assert isinstance(model.get_input_embeddings()				,tf.keras.layers.Layer					)
									if model_class in list_other_models_with_output_ebd:
													__A       =					model.get_output_embeddings()
													assert isinstance(A				,tf.keras.layers.Layer					)
													__A       =					model.get_bias()
													assert name is None
									else:
													__A       =					model.get_output_embeddings()
													assert x is None
													__A       =					model.get_bias()
													assert name is None






	def 							UpperCamelCase_    (			self   :					Union[str, Any]					):
					# TODO JP: Make TransfoXL XLA compliant
					pass






	@slow
	def 							UpperCamelCase_    (			self   :					List[Any]					):
					for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__A       =					TFTransfoXLModel.from_pretrained(A					)
									self.assertIsNotNone(A					)







	@unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss."					)
	def 							UpperCamelCase_    (			self   :					Union[str, Any]					):
					pass





@require_tf
class 				UpperCAmelCase (    unittest.TestCase    ):




	'''simple docstring'''





	@unittest.skip("Skip test until #12651 is resolved."					)
	@slow
	def 							UpperCamelCase_    (			self   :					List[Any]					):
					__A       =					TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103"					)
					# fmt: off
					__A       =					tf.convert_to_tensor([[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0]]				,dtype=tf.intaa					)  # noqa: E231
					# fmt: on
					#  In 1991 , the remains of Russian Tsar Nicholas II and his family
					#  ( except for Alexei and Maria ) are discovered .
					#  The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
					#  remainder of the story . 1883 Western Siberia ,
					#  a young Grigori Rasputin is asked by his father and a group of men to perform magic .
					#  Rasputin has a vision and denounces one of the men as a horse thief . Although his
					#  father initially slaps him for making such an accusation , Rasputin watches as the
					#  man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
					#  the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
					#  with people , even a bishop , begging for his blessing . <eod> </s> <eos>

					# fmt: off
					__A       =					[33,12_97,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,22,17_06,17,2_00_98,5,32_15,21,37,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,62_24,8_31,1_60_02,2,8,6_03,7_89_67,2_95_46,23,8_03,20,25,4_16,5,8,2_32,4,2_77,6,18_55,46_01,3,2_95_46,54,8,36_09,5,5_72_11,49,4,1,2_77,18,8,17_55,1_56_91,3,3_41,25,4_16,6_93,4_25_73,71,17,4_01,94,31,1_79_19,2,2_95_46,78_73,18,1,4_35,23,1_10_11,7_55,5,51_67,3,79_83,98,84,2,2_95_46,32_67,8,36_09,4,1,48_65,10_75,2,60_87,71,6,3_46,8,58_54,3,2_95_46,8_24,14_00,18_68,2,19,1_60,2,3_11,8,54_96,2,2_09_20,17,25,1_50_97,3,24,24,0,33,1,18_57,2,1,10_09,4,11_09,1_17_39,47_62,3_58,5,25,2_45,28,11_10,3,13,10_41,4,24,6_03,4_90,2,7_14_77,2_00_98,10_44_47,2,2_09_61,1,26_04,4,1,3_29,3,0]  # noqa: E231
					# fmt: on
					#  In 1991, the remains of Russian Tsar Nicholas II and his family (
					#  except for Alexei and Maria ) are discovered. The voice of young son,
					#  Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
					#  1883 Western Siberia, a young Grigori Rasputin is asked by his father
					#  and a group of men to perform magic. Rasputin has a vision and
					#  denounces one of the men as a horse thief. Although his father initially
					#  slaps him for making such an accusation, Rasputin watches as the man
					#  is chased outside and beaten. Twenty years later, Rasputin sees a vision
					#  of the Virgin Mary, prompting him to become a priest.
					#  Rasputin quickly becomes famous, with people, even a bishop, begging for
					#  his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
					# Nicholas II and his family were discovered. The voice of <unk> young son,
					# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

					__A       =					model.generate(A				,max_length=2_00				,do_sample=A					)
					self.assertListEqual(output_ids[0].numpy().tolist()				,A					)




'''simple docstring'''



import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
      import jax

      from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel





class   UpperCAmelCase_    (unittest.TestCase    ):





    """simple docstring"""






    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_=5     ,	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.0_2     ,	)							->	Optional[int]:
         __lowerCamelCase  :      Optional[int]														=						parent
         __lowerCamelCase  :      Dict														=						batch_size
         __lowerCamelCase  :      int														=						image_size
         __lowerCamelCase  :      List[str]														=						patch_size
         __lowerCamelCase  :      Optional[int]														=						num_channels
         __lowerCamelCase  :      Any														=						is_training
         __lowerCamelCase  :      Dict														=						use_labels
         __lowerCamelCase  :      List[Any]														=						hidden_size
         __lowerCamelCase  :      List[Any]														=						num_hidden_layers
         __lowerCamelCase  :      Optional[Any]														=						num_attention_heads
         __lowerCamelCase  :      Dict														=						intermediate_size
         __lowerCamelCase  :      Union[str, Any]														=						hidden_act
         __lowerCamelCase  :      Optional[int]														=						hidden_dropout_prob
         __lowerCamelCase  :      Tuple														=						attention_probs_dropout_prob
         __lowerCamelCase  :      str														=						type_sequence_label_size
         __lowerCamelCase  :      List[str]														=						initializer_range

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         __lowerCamelCase  :      str														=						(image_size // patch_size) ** 2
         __lowerCamelCase  :      Optional[int]														=						num_patches + 1







    def  lowercase_							(				self      )							->	Union[str, Any]:
         __lowerCamelCase  :      int														=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

         __lowerCamelCase  :      Optional[int]														=						ViTConfig(
             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     ,	)

         return config, pixel_values







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Union[str, Any]:
         __lowerCamelCase  :      Union[str, Any]														=						FlaxViTModel(config=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      str														=						model(SCREAMING_SNAKE_CASE_      )
         # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
         __lowerCamelCase  :      str														=						(self.image_size, self.image_size)
         __lowerCamelCase  :      str														=						(self.patch_size, self.patch_size)
         __lowerCamelCase  :      Any														=						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         self.parent.assertEqual(result.last_hidden_state.shape     ,	(self.batch_size, num_patches + 1, self.hidden_size)      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         __lowerCamelCase  :      Tuple														=						self.type_sequence_label_size
         __lowerCamelCase  :      Any														=						FlaxViTForImageClassification(config=SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Dict														=						model(SCREAMING_SNAKE_CASE_      )
         self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, self.type_sequence_label_size)      )

         # test greyscale images
         __lowerCamelCase  :      List[str]														=						1
         __lowerCamelCase  :      List[Any]														=						FlaxViTForImageClassification(SCREAMING_SNAKE_CASE_      )

         __lowerCamelCase  :      str														=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
         __lowerCamelCase  :      List[Any]														=						model(SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	Optional[int]:
         __lowerCamelCase  :      List[Any]														=						self.prepare_config_and_inputs()
         (
             (
             __lowerCamelCase
         )							,			(
             __lowerCamelCase
         )							,			
         )  :      int														=						config_and_inputs
         __lowerCamelCase  :      Union[str, Any]														=						{'pixel_values': pixel_values}
         return config, inputs_dict







@require_flax
class   UpperCAmelCase_    (_UpperCAmelCase   ,						unittest.TestCase    ):





    """simple docstring"""






    lowerCamelCase    :   str					=     (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()







    def  lowercase_							(				self      )							->	None:
         __lowerCamelCase  :      str														=						FlaxViTModelTester(self      )
         __lowerCamelCase  :      Union[str, Any]														=						ConfigTester(self     ,	config_class=SCREAMING_SNAKE_CASE_     ,	has_text_modality=SCREAMING_SNAKE_CASE_     ,	hidden_size=37      )







    def  lowercase_							(				self      )							->	List[Any]:
         self.config_tester.run_common_tests()







    def  lowercase_							(				self      )							->	Optional[Any]:
         __lowerCamelCase  :      Optional[int]														=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	Any:
         __lowerCamelCase  :      List[Any]														=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	Optional[Any]:
         __lowerCamelCase							,			__lowerCamelCase  :      Optional[int]														=						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __lowerCamelCase  :      Optional[Any]														=						model_class(SCREAMING_SNAKE_CASE_      )
              __lowerCamelCase  :      Dict														=						inspect.signature(model.__call__      )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __lowerCamelCase  :      List[str]														=						[*signature.parameters.keys()]

              __lowerCamelCase  :      Optional[int]														=						['pixel_values']
              self.assertListEqual(arg_names[:1]     ,	SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	Any:
         __lowerCamelCase							,			__lowerCamelCase  :      Dict														=						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__      ):
                   __lowerCamelCase  :      List[Any]														=						self._prepare_for_class(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
                   __lowerCamelCase  :      Optional[int]														=						model_class(SCREAMING_SNAKE_CASE_      )

                   @jax.jit
                   def model_jitted(SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      ):
                        return model(pixel_values=SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )

                   with self.subTest('JIT Enabled'      ):
                        __lowerCamelCase  :      Optional[int]														=						model_jitted(**SCREAMING_SNAKE_CASE_      ).to_tuple()

                   with self.subTest('JIT Disabled'      ):
                        with jax.disable_jit():
                             __lowerCamelCase  :      Union[str, Any]														=						model_jitted(**SCREAMING_SNAKE_CASE_      ).to_tuple()

                   self.assertEqual(len(SCREAMING_SNAKE_CASE_      )     ,	len(SCREAMING_SNAKE_CASE_      )      )
                   for jitted_output, output in zip(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ):
                        self.assertEqual(jitted_output.shape     ,	output.shape      )







    @slow
    def  lowercase_							(				self      )							->	List[Any]:
         for model_class_name in self.all_model_classes:
              __lowerCamelCase  :      Union[str, Any]														=						model_class_name.from_pretrained('google/vit-base-patch16-224'      )
              __lowerCamelCase  :      Union[str, Any]														=						model(np.ones((1, 3, 2_24, 2_24)      )      )
              self.assertIsNotNone(SCREAMING_SNAKE_CASE_      )






