



"""simple docstring"""







import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import (
							    FalconForCausalLM,
							    FalconForQuestionAnswering,
							    FalconForSequenceClassification,
							    FalconForTokenClassification,
							    FalconModel,
							)
class        __A       :







		'''simple docstring'''





		def __init__(	self						:  int			,_snake_case						:  Optional[Any]			,_snake_case						:  List[str]=3			,_snake_case						:  Optional[int]=7			,_snake_case						:  int=True			,_snake_case						:  Tuple=True			,_snake_case						:  List[Any]=False			,_snake_case						:  Dict=True			,_snake_case						:  Tuple=99			,_snake_case						:  int=32			,_snake_case						:  Optional[Any]=5			,_snake_case						:  List[Any]=4			,_snake_case						:  Tuple=37			,_snake_case						:  Any="gelu"			,_snake_case						:  Union[str, Any]=0.1			,_snake_case						:  Optional[int]=0.1			,_snake_case						:  List[str]=512			,_snake_case						:  str=16			,_snake_case						:  Dict=2			,_snake_case						:  List[str]=0.02			,_snake_case						:  Any=3			,_snake_case						:  Optional[Any]=4			,_snake_case						:  List[Any]=None			,)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    int				=			parent
				lowercase__   :    Union[str, Any]				=			batch_size
				lowercase__   :    Optional[Any]				=			seq_length
				lowercase__   :    Optional[Any]				=			is_training
				lowercase__   :    Optional[Any]				=			use_input_mask
				lowercase__   :    Optional[int]				=			use_token_type_ids
				lowercase__   :    List[str]				=			use_labels
				lowercase__   :    List[Any]				=			vocab_size
				lowercase__   :    str				=			hidden_size
				lowercase__   :    int				=			num_hidden_layers
				lowercase__   :    List[Any]				=			num_attention_heads
				lowercase__   :    Union[str, Any]				=			intermediate_size
				lowercase__   :    Union[str, Any]				=			hidden_act
				lowercase__   :    str				=			hidden_dropout_prob
				lowercase__   :    Any				=			attention_probs_dropout_prob
				lowercase__   :    Tuple				=			max_position_embeddings
				lowercase__   :    Optional[Any]				=			type_vocab_size
				lowercase__   :    Tuple				=			type_sequence_label_size
				lowercase__   :    List[str]				=			initializer_range
				lowercase__   :    Any				=			num_labels
				lowercase__   :    str				=			num_choices
				lowercase__   :    Dict				=			scope







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			ids_tensor([self.batch_size, self.seq_length]			,self.vocab_size						)

				lowercase__   :    int				=			None
				if self.use_input_mask:
						lowercase__   :    str				=			random_attention_mask([self.batch_size, self.seq_length]						)

				lowercase__   :    Dict				=			None

				lowercase__   :    int				=			None
				lowercase__   :    List[str]				=			None
				lowercase__   :    int				=			None
				if self.use_labels:
						lowercase__   :    List[Any]				=			ids_tensor([self.batch_size]			,self.type_sequence_label_size						)
						lowercase__   :    Any				=			ids_tensor([self.batch_size, self.seq_length]			,self.num_labels						)
						lowercase__   :    str				=			ids_tensor([self.batch_size]			,self.num_choices						)

				lowercase__   :    Optional[int]				=			self.get_config()

				return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Union[str, Any]:






				"""simple docstring"""



				return FalconConfig(
				    vocab_size=self.vocab_size			,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			,max_position_embeddings=self.max_position_embeddings			,type_vocab_size=self.type_vocab_size			,is_decoder=_snake_case			,initializer_range=self.initializer_range			,pad_token_id=1			,new_decoder_architecture=_snake_case			,)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]			,_snake_case						:  List[str]			,_snake_case						:  Any			,_snake_case						:  str			,_snake_case						:  Optional[Any]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			FalconModel(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    str				=			model(_snake_case			,attention_mask=_snake_case						)
				lowercase__   :    Union[str, Any]				=			model(_snake_case						)
				self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)						)







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  Any			,_snake_case						:  Optional[int]			,_snake_case						:  List[str]			,_snake_case						:  Tuple			,_snake_case						:  Dict			,_snake_case						:  Dict			,_snake_case						:  Dict			,_snake_case						:  Any			,_snake_case						:  Union[str, Any]			,)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    str				=			True
				lowercase__   :    Dict				=			FalconModel(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Optional[Any]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,)
				lowercase__   :    Optional[Any]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,)
				lowercase__   :    Dict				=			model(_snake_case			,attention_mask=_snake_case						)
				self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)						)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  Tuple			,_snake_case						:  str			,_snake_case						:  List[Any]			,_snake_case						:  Optional[Any]			,_snake_case						:  Union[str, Any]			,_snake_case						:  str			,_snake_case						:  Tuple			,_snake_case						:  Union[str, Any]			,_snake_case						:  str			,)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    List[str]				=			FalconForCausalLM(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Any				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.seq_length, self.vocab_size)						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  str			,_snake_case						:  int			,_snake_case						:  int			,_snake_case						:  Tuple			,_snake_case						:  Optional[int]			,_snake_case						:  Dict			,_snake_case						:  Dict			,_snake_case						:  str			,_snake_case						:  Union[str, Any]			,)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			True
				lowercase__   :    str				=			True
				lowercase__   :    str				=			FalconForCausalLM(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()

				# first forward pass
				lowercase__   :    Any				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,use_cache=_snake_case			,)
				lowercase__   :    Union[str, Any]				=			outputs.past_key_values

				# create hypothetical multiple next token and extent to next_input_ids
				lowercase__   :    Any				=			ids_tensor((self.batch_size, 3)			,config.vocab_size						)
				lowercase__   :    List[str]				=			ids_tensor((self.batch_size, 3)			,vocab_size=2						)

				# append to next input_ids and
				lowercase__   :    Union[str, Any]				=			torch.cat([input_ids, next_tokens]			,dim=-1						)
				lowercase__   :    str				=			torch.cat([input_mask, next_mask]			,dim=-1						)

				lowercase__   :    List[str]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,output_hidden_states=_snake_case			,)['''hidden_states'''][0]
				lowercase__   :    List[str]				=			model(
				    _snake_case			,attention_mask=_snake_case			,encoder_hidden_states=_snake_case			,encoder_attention_mask=_snake_case			,past_key_values=_snake_case			,output_hidden_states=_snake_case			,)['''hidden_states'''][0]

				# select random slice
				lowercase__   :    int				=			ids_tensor((1,)			,output_from_past.shape[-1]						).item()
				lowercase__   :    str				=			output_from_no_past[:, -3:, random_slice_idx].detach()
				lowercase__   :    Tuple				=			output_from_past[:, :, random_slice_idx].detach()

				self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]						)

				# test that outputs are equal for slice
				self.parent.assertTrue(torch.allclose(_snake_case			,_snake_case			,atol=1e-3						)						)







		def 					UpperCAmelCase    (	self						:  Any						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    str				=			self.prepare_config_and_inputs()
				(
				    (
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			(
				    lowercase__
				)		,			
				)   :    Optional[Any]				=			config_and_inputs
				lowercase__   :    Union[str, Any]				=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
				return config, inputs_dict





@require_torch
class        __A       (	A_     ,A_     ,A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Optional[int]   	=				(
		    (
		        FalconModel,
		        FalconForCausalLM,
		        FalconForSequenceClassification,
		        FalconForTokenClassification,
		        FalconForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase			:					List[Any]   	=				(FalconForCausalLM,) if is_torch_available() else ()
		lowerCAmelCase			:					int   	=				(
		    {
		        "feature-extraction": FalconModel,
		        "text-classification": FalconForSequenceClassification,
		        "text-generation": FalconForCausalLM,
		        "question-answering": FalconForQuestionAnswering,
		        "token-classification": FalconForTokenClassification,
		        "zero-shot": FalconForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		lowerCAmelCase			:					Dict   	=				False
		lowerCAmelCase			:					List[str]   	=				False







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    Tuple				=			FalconModelTester(self						)
				lowercase__   :    Any				=			ConfigTester(self			,config_class=_snake_case			,hidden_size=37						)







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Dict:






				"""simple docstring"""



				self.config_tester.run_common_tests()







		def 					UpperCAmelCase    (	self						:  Any						)					->		int:






				"""simple docstring"""



				lowercase__   :    int				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		int:






				"""simple docstring"""



				lowercase__		,			*lowercase__   :    Dict				=			self.model_tester.prepare_config_and_inputs()
				for alibi in [True, False]:
						lowercase__   :    Dict				=			alibi
						self.model_tester.create_and_check_model(_snake_case			,*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Union[str, Any]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    str				=			3
				lowercase__   :    Optional[int]				=			input_dict['''input_ids''']
				lowercase__   :    Optional[Any]				=			input_ids.ne(1						).to(_snake_case						)
				lowercase__   :    List[str]				=			ids_tensor([self.model_tester.batch_size]			,self.model_tester.type_sequence_label_size						)
				lowercase__   :    int				=			FalconForSequenceClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    List[Any]				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.assertEqual(result.logits.shape			,(self.model_tester.batch_size, self.model_tester.num_labels)						)







		def 					UpperCAmelCase    (	self						:  str						)					->		List[str]:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Any				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Union[str, Any]				=			3
				lowercase__   :    str				=			'''single_label_classification'''
				lowercase__   :    Tuple				=			input_dict['''input_ids''']
				lowercase__   :    str				=			input_ids.ne(1						).to(_snake_case						)
				lowercase__   :    Optional[int]				=			ids_tensor([self.model_tester.batch_size]			,self.model_tester.type_sequence_label_size						)
				lowercase__   :    Union[str, Any]				=			FalconForSequenceClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    List[Any]				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.assertEqual(result.logits.shape			,(self.model_tester.batch_size, self.model_tester.num_labels)						)







		def 					UpperCAmelCase    (	self						:  str						)					->		str:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Tuple				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Union[str, Any]				=			input_dict['''input_ids''']
				lowercase__   :    Union[str, Any]				=			FalconForCausalLM(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Optional[Any]				=			model(_snake_case			,use_cache=_snake_case						)
				lowercase__   :    int				=			input_ids.shape[0]
				lowercase__   :    List[str]				=			model._convert_to_rw_cache(result.past_key_values						)
				lowercase__   :    List[str]				=			model._convert_cache_to_standard_format(_snake_case			,_snake_case						)
				for layer in range(len(_snake_case						)						):
						for tensor_idx in range(2						):
								self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3						)
								self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4						)
								self.assertTrue(
								    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]						)						)







		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Dict:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Optional[Any]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Optional[int]				=			3
				lowercase__   :    Dict				=			'''multi_label_classification'''
				lowercase__   :    Optional[int]				=			input_dict['''input_ids''']
				lowercase__   :    Dict				=			input_ids.ne(1						).to(_snake_case						)
				lowercase__   :    Any				=			ids_tensor(
				    [self.model_tester.batch_size, config.num_labels]			,self.model_tester.type_sequence_label_size						).to(torch.float						)
				lowercase__   :    Tuple				=			FalconForSequenceClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Tuple				=			model(_snake_case			,attention_mask=_snake_case			,labels=_snake_case						)
				self.assertEqual(result.logits.shape			,(self.model_tester.batch_size, self.model_tester.num_labels)						)







		def 					UpperCAmelCase    (	self						:  str						)					->		Optional[Any]:






				"""simple docstring"""



				for model_class in self.all_generative_model_classes:
						lowercase__		,			lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()

						# If it doesn't support cache, pass the test
						if not hasattr(_snake_case			,'''use_cache'''						):
								return

						lowercase__   :    Optional[Any]				=			model_class(_snake_case						).to(_snake_case						)
						if "use_cache" not in inputs:
								lowercase__   :    Optional[int]				=			True
						lowercase__   :    List[str]				=			model(**_snake_case						)

						# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
						if "past_key_values" not in outputs:
								return

						lowercase__   :    Tuple				=			(
						    getattr(_snake_case			,'''decoder_layers'''			,_snake_case						)
						    or getattr(_snake_case			,'''num_decoder_layers'''			,_snake_case						)
						    or config.num_hidden_layers
						)
						lowercase__   :    Optional[int]				=			getattr(_snake_case			,'''num_kv_heads'''			,config.num_attention_heads						)
						lowercase__   :    Optional[int]				=			getattr(_snake_case			,'''d_model'''			,config.hidden_size						)
						lowercase__   :    Union[str, Any]				=			embed_dim // num_attention_heads

						lowercase__   :    Union[str, Any]				=			outputs['''past_key_values''']
						self.assertEqual(len(_snake_case						)			,_snake_case						)

						lowercase__		,			lowercase__   :    Union[str, Any]				=			inputs['''input_ids'''].shape
						for i in range(_snake_case						):
								if config.new_decoder_architecture:
										lowercase__   :    Union[str, Any]				=			config.num_attention_heads
								elif config.multi_query:
										lowercase__   :    Union[str, Any]				=			1
								self.assertEqual(len(past_kv[0]						)			,2						)  # K V for the decoder = 2
								self.assertEqual(
								    past_kv[i][0].shape			,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)
								self.assertEqual(
								    past_kv[i][1].shape			,(batch_size, num_attention_heads, seq_length, per_head_embed_dim)						)





@require_torch
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@slow
		def 					UpperCAmelCase    (	self						:  Any						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Dict				=			AutoTokenizer.from_pretrained('''Rocketknight1/falcon-rw-1b'''						)
				lowercase__   :    int				=			FalconForCausalLM.from_pretrained('''Rocketknight1/falcon-rw-1b'''						)
				model.eval()
				model.to(_snake_case						)
				lowercase__   :    int				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

				lowercase__   :    List[Any]				=			(
				    '''My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.'''
				)

				lowercase__   :    Dict				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=19						)
				lowercase__   :    Optional[int]				=			tokenizer.batch_decode(_snake_case						)[0]

				self.assertEqual(_snake_case			,_snake_case						)







		@slow
		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		Optional[Any]:






				"""simple docstring"""



				for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
						lowercase__   :    List[Any]				=			AutoTokenizer.from_pretrained(_snake_case						)
						lowercase__   :    List[Any]				=			FalconForCausalLM.from_pretrained(_snake_case						)
						model.eval()
						model.to(_snake_case						)
						lowercase__   :    Optional[int]				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

						# We just test that these run without errors - the models are randomly initialized
						# and so the actual text outputs will be garbage
						model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=4						)
						model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=4						)
						model.generate(**_snake_case			,num_beams=2			,max_new_tokens=4						)







		@slow
		def 					UpperCAmelCase    (	self						:  int						)					->		Any:






				"""simple docstring"""



				with torch.no_grad():
						for repo in [
						    "Rocketknight1/falcon-rw-1b",
						    "Rocketknight1/tiny-random-falcon-7b",
						    "Rocketknight1/tiny-random-falcon-40b",
						]:
								lowercase__   :    Any				=			AutoTokenizer.from_pretrained(_snake_case						)
								lowercase__   :    Optional[Any]				=			FalconForCausalLM.from_pretrained(_snake_case						)
								model.eval()
								model.to(device=_snake_case						)
								lowercase__   :    Any				=			tokenizer('''My favorite food is'''			,return_tensors='''pt'''						).to(_snake_case						)

								# Test results are the same with and without cache
								lowercase__   :    Dict				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=20			,use_cache=_snake_case						)
								lowercase__   :    Tuple				=			model.generate(**_snake_case			,do_sample=_snake_case			,max_new_tokens=20			,use_cache=_snake_case						)
								self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0						)





"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor


lowerCAmelCase_   						=   logging.get_logger(__name__)
class        __A       (	A_    ):







		'''simple docstring'''





		def __init__(	self						:  Dict			,*_snake_case						:  Any			,**_snake_case						:  str						)					->		None:






				"""simple docstring"""



				warnings.warn(
				    '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
				    ''' Please use MobileViTImageProcessor instead.'''			,_snake_case			,)
				super().__init__(*_snake_case			,**_snake_case						)
