


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






		def __init__(						self				:     Any   ,  UpperCAmelCase				:     Dict   ,  UpperCAmelCase				:     Optional[Any]=3   ,  UpperCAmelCase				:     Union[str, Any]=7   ,  UpperCAmelCase				:     List[Any]=True   ,  UpperCAmelCase				:     Dict=True   ,  UpperCAmelCase				:     Union[str, Any]=False   ,  UpperCAmelCase				:     Any=True   ,  UpperCAmelCase				:     List[str]=99   ,  UpperCAmelCase				:     Optional[int]=32   ,  UpperCAmelCase				:     Optional[Any]=5   ,  UpperCAmelCase				:     Union[str, Any]=4   ,  UpperCAmelCase				:     int=37   ,  UpperCAmelCase				:     int="gelu"   ,  UpperCAmelCase				:     List[Any]=0.1   ,  UpperCAmelCase				:     List[Any]=0.1   ,  UpperCAmelCase				:     Optional[Any]=5_12   ,  UpperCAmelCase				:     Tuple=16   ,  UpperCAmelCase				:     str=2   ,  UpperCAmelCase				:     Optional[Any]=0.02   ,  UpperCAmelCase				:     Optional[Any]=3   ,  UpperCAmelCase				:     Union[str, Any]=4   ,  UpperCAmelCase				:     str=None   ,  ):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						parent
				SCREAMING_SNAKE_CASE_				:int				     =						batch_size
				SCREAMING_SNAKE_CASE_				:Dict				     =						seq_length
				SCREAMING_SNAKE_CASE_				:int				     =						is_training
				SCREAMING_SNAKE_CASE_				:Any				     =						use_input_mask
				SCREAMING_SNAKE_CASE_				:str				     =						use_token_type_ids
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						use_labels
				SCREAMING_SNAKE_CASE_				:str				     =						vocab_size
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						hidden_size
				SCREAMING_SNAKE_CASE_				:Any				     =						num_hidden_layers
				SCREAMING_SNAKE_CASE_				:int				     =						num_attention_heads
				SCREAMING_SNAKE_CASE_				:List[str]				     =						intermediate_size
				SCREAMING_SNAKE_CASE_				:Dict				     =						hidden_act
				SCREAMING_SNAKE_CASE_				:str				     =						hidden_dropout_prob
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						max_position_embeddings
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						type_vocab_size
				SCREAMING_SNAKE_CASE_				:int				     =						type_sequence_label_size
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						initializer_range
				SCREAMING_SNAKE_CASE_				:Dict				     =						num_labels
				SCREAMING_SNAKE_CASE_				:str				     =						num_choices
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						scope






		def _snake_case		(						self				:     Optional[Any]):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						ids_tensor([self.batch_size, self.seq_length]   ,  self.vocab_size)

				SCREAMING_SNAKE_CASE_				:Any				     =						None
				if self.use_input_mask:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						random_attention_mask([self.batch_size, self.seq_length])

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						None

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

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						self.get_config()

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






		def _snake_case		(						self				:     List[str]):
				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=UpperCAmelCase   ,  initializer_range=self.initializer_range   ,  pad_token_id=1   ,  new_decoder_architecture=UpperCAmelCase   ,  )






		def _snake_case		(						self				:     Any   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     str   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Tuple   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     List[Any]):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						FalconModel(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:int				     =						model(UpperCAmelCase   ,  attention_mask=UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						model(UpperCAmelCase)
				self.parent.assertEqual(result.last_hidden_state.shape   ,  (self.batch_size, self.seq_length, self.hidden_size))






		def _snake_case		(						self				:     Tuple   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Union[str, Any]   ,  UpperCAmelCase				:     Union[str, Any]   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     Union[str, Any]   ,  UpperCAmelCase				:     Tuple   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Tuple   ,  UpperCAmelCase				:     List[Any]   ,  ):
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						True
				SCREAMING_SNAKE_CASE_				:str				     =						FalconModel(UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						model(
				    UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  encoder_hidden_states=UpperCAmelCase   ,  encoder_attention_mask=UpperCAmelCase   ,  )
				SCREAMING_SNAKE_CASE_				:List[str]				     =						model(
				    UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  encoder_hidden_states=UpperCAmelCase   ,  )
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						model(UpperCAmelCase   ,  attention_mask=UpperCAmelCase)
				self.parent.assertEqual(result.last_hidden_state.shape   ,  (self.batch_size, self.seq_length, self.hidden_size))






		def _snake_case		(						self				:     Dict   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     List[str]   ,  UpperCAmelCase				:     List[Any]   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     List[str]   ,  UpperCAmelCase				:     int   ,  ):
				SCREAMING_SNAKE_CASE_				:Any				     =						FalconForCausalLM(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						model(UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  labels=UpperCAmelCase)
				self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.seq_length, self.vocab_size))






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     int   ,  UpperCAmelCase				:     Union[str, Any]   ,  UpperCAmelCase				:     str   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     Any   ,  UpperCAmelCase				:     Optional[Any]   ,  UpperCAmelCase				:     Optional[int]   ,  ):
				SCREAMING_SNAKE_CASE_				:List[str]				     =						True
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						True
				SCREAMING_SNAKE_CASE_				:List[str]				     =						FalconForCausalLM(config=UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()

				# first forward pass
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						model(
				    UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  encoder_hidden_states=UpperCAmelCase   ,  encoder_attention_mask=UpperCAmelCase   ,  use_cache=UpperCAmelCase   ,  )
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						outputs.past_key_values

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

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

				SCREAMING_SNAKE_CASE_				:Tuple				     =						model(
				    UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  encoder_hidden_states=UpperCAmelCase   ,  encoder_attention_mask=UpperCAmelCase   ,  output_hidden_states=UpperCAmelCase   ,  )["hidden_states"][0]
				SCREAMING_SNAKE_CASE_				:Dict				     =						model(
				    UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  encoder_hidden_states=UpperCAmelCase   ,  encoder_attention_mask=UpperCAmelCase   ,  past_key_values=UpperCAmelCase   ,  output_hidden_states=UpperCAmelCase   ,  )["hidden_states"][0]

				# select random slice
				SCREAMING_SNAKE_CASE_				:Tuple				     =						ids_tensor((1,)   ,  output_from_past.shape[-1]).item()
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						output_from_no_past[:, -3:, random_slice_idx].detach()
				SCREAMING_SNAKE_CASE_				:Any				     =						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(UpperCAmelCase   ,  UpperCAmelCase   ,  atol=1E-3))







		def _snake_case		(						self				:     List[str]):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						self.prepare_config_and_inputs()
				(
				    (
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				(
				    SCREAMING_SNAKE_CASE_
				)     ,				
				)				:Dict				     =						config_and_inputs
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						{"input_ids": input_ids, "attention_mask": input_mask}
				return config, inputs_dict




@require_torch
class 						_UpperCAmelCase      (     lowercase		,		lowercase		,		lowercase		,		unittest.TestCase							):
		lowerCamelCase_	:			List[str]       			=  (
		    (
		        FalconModel,
		        FalconForCausalLM,
		        FalconForSequenceClassification,
		        FalconForTokenClassification,
		        FalconForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		lowerCamelCase_	:			List[str]       			=  (FalconForCausalLM,) if is_torch_available() else ()
		lowerCamelCase_	:			Any       			=  (
		    {
		        """feature-extraction""": FalconModel,
		        """text-classification""": FalconForSequenceClassification,
		        """text-generation""": FalconForCausalLM,
		        """question-answering""": FalconForQuestionAnswering,
		        """token-classification""": FalconForTokenClassification,
		        """zero-shot""": FalconForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		lowerCamelCase_	:			Optional[Any]       			=  False
		lowerCamelCase_	:			str       			=  False






		def _snake_case		(						self				:     Any):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						FalconModelTester(self)
				SCREAMING_SNAKE_CASE_				:Tuple				     =						ConfigTester(self   ,  config_class=UpperCAmelCase   ,  hidden_size=37)






		def _snake_case		(						self				:     Union[str, Any]):
				self.config_tester.run_common_tests()






		def _snake_case		(						self				:     Dict):
				SCREAMING_SNAKE_CASE_				:int				     =						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*UpperCAmelCase)






		def _snake_case		(						self				:     int):
				SCREAMING_SNAKE_CASE_     ,				*SCREAMING_SNAKE_CASE_				:Dict				     =						self.model_tester.prepare_config_and_inputs()
				for alibi in [True, False]:
						SCREAMING_SNAKE_CASE_				:str				     =						alibi
						self.model_tester.create_and_check_model(UpperCAmelCase   ,  *UpperCAmelCase)






		def _snake_case		(						self				:     List[Any]):
				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:str				     =						self.model_tester.prepare_config_and_inputs_for_common()
				SCREAMING_SNAKE_CASE_				:str				     =						3
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						input_dict["input_ids"]
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						input_ids.ne(1).to(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Tuple				     =						ids_tensor([self.model_tester.batch_size]   ,  self.model_tester.type_sequence_label_size)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						FalconForSequenceClassification(UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Dict				     =						model(UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  labels=UpperCAmelCase)
				self.assertEqual(result.logits.shape   ,  (self.model_tester.batch_size, self.model_tester.num_labels))






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






		def _snake_case		(						self				:     int):
				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:List[Any]				     =						self.model_tester.prepare_config_and_inputs_for_common()
				SCREAMING_SNAKE_CASE_				:Tuple				     =						input_dict["input_ids"]
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						FalconForCausalLM(UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:Any				     =						model(UpperCAmelCase   ,  use_cache=UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						input_ids.shape[0]
				SCREAMING_SNAKE_CASE_				:str				     =						model._convert_to_rw_cache(result.past_key_values)
				SCREAMING_SNAKE_CASE_				:Dict				     =						model._convert_cache_to_standard_format(UpperCAmelCase   ,  UpperCAmelCase)
				for layer in range(len(UpperCAmelCase)):
						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 _snake_case		(						self				:     int):
				SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						self.model_tester.prepare_config_and_inputs_for_common()
				SCREAMING_SNAKE_CASE_				:Dict				     =						3
				SCREAMING_SNAKE_CASE_				:Dict				     =						"multi_label_classification"
				SCREAMING_SNAKE_CASE_				:List[str]				     =						input_dict["input_ids"]
				SCREAMING_SNAKE_CASE_				:str				     =						input_ids.ne(1).to(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:int				     =						ids_tensor(
				    [self.model_tester.batch_size, config.num_labels]   ,  self.model_tester.type_sequence_label_size).to(torch.float)
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						FalconForSequenceClassification(UpperCAmelCase)
				model.to(UpperCAmelCase)
				model.eval()
				SCREAMING_SNAKE_CASE_				:str				     =						model(UpperCAmelCase   ,  attention_mask=UpperCAmelCase   ,  labels=UpperCAmelCase)
				self.assertEqual(result.logits.shape   ,  (self.model_tester.batch_size, self.model_tester.num_labels))







		def _snake_case		(						self				:     List[Any]):
				# Falcon can have different numbers of KV-heads than the number of query heads, so we need
				# to override this test to use the right head counts.
				for model_class in self.all_generative_model_classes:
						SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:int				     =						self.model_tester.prepare_config_and_inputs_for_common()

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

						SCREAMING_SNAKE_CASE_				:int				     =						model_class(UpperCAmelCase).to(UpperCAmelCase)
						if "use_cache" not in inputs:
								SCREAMING_SNAKE_CASE_				:Dict				     =						True
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						model(**UpperCAmelCase)

						# 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

						SCREAMING_SNAKE_CASE_				:Dict				     =						(
						    getattr(UpperCAmelCase   ,  "decoder_layers"   ,  UpperCAmelCase)
						    or getattr(UpperCAmelCase   ,  "num_decoder_layers"   ,  UpperCAmelCase)
						    or config.num_hidden_layers
						)
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						getattr(UpperCAmelCase   ,  "num_kv_heads"   ,  config.num_attention_heads)
						SCREAMING_SNAKE_CASE_				:List[str]				     =						getattr(UpperCAmelCase   ,  "d_model"   ,  config.hidden_size)
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						embed_dim // num_attention_heads

						SCREAMING_SNAKE_CASE_				:str				     =						outputs["past_key_values"]
						self.assertEqual(len(UpperCAmelCase)   ,  UpperCAmelCase)

						SCREAMING_SNAKE_CASE_     ,				SCREAMING_SNAKE_CASE_				:Tuple				     =						inputs["input_ids"].shape
						for i in range(UpperCAmelCase):
								if config.new_decoder_architecture:
										SCREAMING_SNAKE_CASE_				:Any				     =						config.num_attention_heads
								elif config.multi_query:
										SCREAMING_SNAKE_CASE_				:List[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 						_UpperCAmelCase      (     unittest.TestCase							):






		@slow
		def _snake_case		(						self				:     int):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b")
				SCREAMING_SNAKE_CASE_				:int				     =						FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b")
				model.eval()
				model.to(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						tokenizer("My favorite food is"   ,  return_tensors="pt").to(UpperCAmelCase)

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

				SCREAMING_SNAKE_CASE_				:List[Any]				     =						model.generate(**UpperCAmelCase   ,  do_sample=UpperCAmelCase   ,  max_new_tokens=19)
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						tokenizer.batch_decode(UpperCAmelCase)[0]

				self.assertEqual(UpperCAmelCase   ,  UpperCAmelCase)






		@slow
		def _snake_case		(						self				:     Dict):
				# The big models are way too big for the CI, so we use tiny random models that resemble their
				# architectures but with much smaller and fewer layers
				for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
						SCREAMING_SNAKE_CASE_				:Any				     =						AutoTokenizer.from_pretrained(UpperCAmelCase)
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						FalconForCausalLM.from_pretrained(UpperCAmelCase)
						model.eval()
						model.to(UpperCAmelCase)
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						tokenizer("My favorite food is"   ,  return_tensors="pt").to(UpperCAmelCase)

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







		@slow
		def _snake_case		(						self				:     str):
				# The big models are way too big for the CI, so we use tiny random models that resemble their
				# architectures but with much smaller and fewer layers
				with torch.no_grad():
						for repo in [
						    "Rocketknight1/falcon-rw-1b",
						    "Rocketknight1/tiny-random-falcon-7b",
						    "Rocketknight1/tiny-random-falcon-40b",
						]:
								SCREAMING_SNAKE_CASE_				:List[Any]				     =						AutoTokenizer.from_pretrained(UpperCAmelCase)
								SCREAMING_SNAKE_CASE_				:Tuple				     =						FalconForCausalLM.from_pretrained(UpperCAmelCase)
								model.eval()
								model.to(device=UpperCAmelCase)
								SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						tokenizer("My favorite food is"   ,  return_tensors="pt").to(UpperCAmelCase)

								# Test results are the same with and without cache
								SCREAMING_SNAKE_CASE_				:Any				     =						model.generate(**UpperCAmelCase   ,  do_sample=UpperCAmelCase   ,  max_new_tokens=20   ,  use_cache=UpperCAmelCase)
								SCREAMING_SNAKE_CASE_				:int				     =						model.generate(**UpperCAmelCase   ,  do_sample=UpperCAmelCase   ,  max_new_tokens=20   ,  use_cache=UpperCAmelCase)
								self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0)










import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version(">=", FSDP_PYTORCH_VERSION):
		import torch.distributed.checkpoint as dist_cp
		from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
		from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
		from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
		from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


SCREAMING_SNAKE_CASE__     					=			get_logger(__name__)


def     lowercase	(    a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		os.makedirs(a     , exist_ok=a )
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						model.state_dict()
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin"
						SCREAMING_SNAKE_CASE_				:str				     =						os.path.join(a     , a )
						if accelerator.process_index == 0:
								logger.info(F"Saving model to {output_model_file}" )
								torch.save(a     , a )
								logger.info(F"Model saved to {output_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Tuple				     =						(
						    F"{MODEL_NAME}_rank{accelerator.process_index}.bin"
						    if model_index == 0
						    else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						os.path.join(a     , a )
						logger.info(F"Saving model to {output_model_file}" )
						torch.save(a     , a )
						logger.info(F"Model saved to {output_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:Dict				     =						os.path.join(a     , F"{MODEL_NAME}_{model_index}" )
						os.makedirs(a     , exist_ok=a )
						logger.info(F"Saving model to {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:int				     =						{"model": state_dict}

						dist_cp.save_state_dict(
						    state_dict=a     , storage_writer=dist_cp.FileSystemWriter(a )     , planner=DefaultSavePlanner()     , )
						logger.info(F"Model saved to {ckpt_dir}" )


def     lowercase	(    a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		accelerator.wait_for_everyone()
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						if type(a ) != FSDP and accelerator.process_index != 0:
								if not fsdp_plugin.sync_module_states:
										raise ValueError(
										    "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
										    "initializing FSDP object" )
								return
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						F"{MODEL_NAME}.bin" if model_index == 0 else F"{MODEL_NAME}_{model_index}.bin"
						SCREAMING_SNAKE_CASE_				:int				     =						os.path.join(a     , a )
						logger.info(F"Loading model from {input_model_file}" )
						SCREAMING_SNAKE_CASE_				:Dict				     =						torch.load(a )
						logger.info(F"Model loaded from {input_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:int				     =						(
						    F"{MODEL_NAME}_rank{accelerator.process_index}.bin"
						    if model_index == 0
						    else F"{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:int				     =						os.path.join(a     , a )
						logger.info(F"Loading model from {input_model_file}" )
						SCREAMING_SNAKE_CASE_				:Dict				     =						torch.load(a )
						logger.info(F"Model loaded from {input_model_file}" )
				elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						(
						    os.path.join(a     , F"{MODEL_NAME}_{model_index}" )
						    if F"{MODEL_NAME}" not in input_dir
						    else input_dir
						)
						logger.info(F"Loading model from {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:Any				     =						{"model": model.state_dict()}
						dist_cp.load_state_dict(
						    state_dict=a     , storage_reader=dist_cp.FileSystemReader(a )     , planner=DefaultLoadPlanner()     , )
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						state_dict["model"]
						logger.info(F"Model loaded from {ckpt_dir}" )
				model.load_state_dict(a )


def     lowercase	(    a     , a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		os.makedirs(a     , exist_ok=a )
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				SCREAMING_SNAKE_CASE_				:str				     =						FSDP.optim_state_dict(a     , a )
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						if accelerator.process_index == 0:
								SCREAMING_SNAKE_CASE_				:List[str]				     =						(
								    F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin"
								)
								SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						os.path.join(a     , a )
								logger.info(F"Saving Optimizer state to {output_optimizer_file}" )
								torch.save(a     , a )
								logger.info(F"Optimizer state saved in {output_optimizer_file}" )
				else:
						SCREAMING_SNAKE_CASE_				:Any				     =						os.path.join(a     , F"{OPTIMIZER_NAME}_{optimizer_index}" )
						os.makedirs(a     , exist_ok=a )
						logger.info(F"Saving Optimizer state to {ckpt_dir}" )
						dist_cp.save_state_dict(
						    state_dict={"optimizer": optim_state}     , storage_writer=dist_cp.FileSystemWriter(a )     , planner=DefaultSavePlanner()     , )
						logger.info(F"Optimizer state saved in {ckpt_dir}" )


def     lowercase	(    a     , a     , a     , a     , a     , a=0 ):



		'''simple docstring'''




		accelerator.wait_for_everyone()
		with FSDP.state_dict_type(
		    a     , fsdp_plugin.state_dict_type     , fsdp_plugin.state_dict_config     , fsdp_plugin.optim_state_dict_config ):
				if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
						SCREAMING_SNAKE_CASE_				:List[str]				     =						None
						# below check should work but currently it isn't working (mostly opytorch issue),
						# in the meantime disabling it at the cost of excess memory usage
						# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						(
						    F"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else F"{OPTIMIZER_NAME}_{optimizer_index}.bin"
						)
						SCREAMING_SNAKE_CASE_				:Dict				     =						os.path.join(a     , a )
						logger.info(F"Loading Optimizer state from {input_optimizer_file}" )
						SCREAMING_SNAKE_CASE_				:str				     =						torch.load(a )
						logger.info(F"Optimizer state loaded from {input_optimizer_file}" )
				else:
						SCREAMING_SNAKE_CASE_				:Any				     =						(
						    os.path.join(a     , F"{OPTIMIZER_NAME}_{optimizer_index}" )
						    if F"{OPTIMIZER_NAME}" not in input_dir
						    else input_dir
						)
						logger.info(F"Loading Optimizer from {ckpt_dir}" )
						SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						load_sharded_optimizer_state_dict(
						    model_state_dict=model.state_dict()     , optimizer_key="optimizer"     , storage_reader=dist_cp.FileSystemReader(a )     , )
						SCREAMING_SNAKE_CASE_				:List[str]				     =						optim_state["optimizer"]
						logger.info(F"Optimizer loaded from {ckpt_dir}" )
				SCREAMING_SNAKE_CASE_				:int				     =						FSDP.optim_state_dict_to_load(a     , a     , a )
				optimizer.load_state_dict(a )






